2020. 10. 8. 10:21ㆍTerminology
Generics( 제너릭 )
Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define. You can write code that avoids duplication and expresses its intent in a clear, abstracted manner.
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
let temporaryA = a
a = b
b = temporaryA
}
This function makes use of in-out parameters to swap the values of a and b, as described in In-Out Parameters.
-> type 이 바뀌면 재사용 불가. ( "String"과 "String" 바꾸고 싶다면 String에 해당하는 함수 또 만들어 줘야혀!
func swapTwoStrings(_ a: inout String, _ b: inout String) {
let temporaryA = a
a = b
b = temporaryA
}
func swapTwoDoubles(_ a: inout Double, _ b: inout Double) {
let temporaryA = a
a = b
b = temporaryA
}
->이렇게 말이여 !
It's more useful, and considerably more flexible, to write a single finction that swaps two calues of any type. Generic code enables you to write such a function.
Generic Functions
func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
let temporaryA = a
a = b
b = temporaryA
}
The generic version of function uses a placeholder type name( called T, in this case) instead of and actual type name (such as Int, String, or Double). The placeholder type name doesn't say anything about what T must be, but it does say that both a and b must be of the same type T, whatever T represents.
The actual type to use in place of T is determined each time the swapTwoValues(_: _: )function is called.
The other difference between a generic function and a nongeneric function is that the generic function's name(swapTwoValues(_: _: ) ) is followed by the placeholder type name(T) inside angle brackets(<T>). The brackets tell Swift that T is a placeholder type name within the swapTwoValues(_: _: ) function definition. Because T is a placeholder, Swift dosen't look for an actual type called T.
var someInt = 3
var anotherInt = 107
swapTwoValues(&someInt, &anotherInt)
// someInt is now 107, and anotherInt is now 3
var someString = "hello"
var anotherString = "world"
swapTwoValues(&someString, &anotherString)
// someString is now "world", and anotherString is now "hello"
Type safety
In computer science, type safety is the extent to which a programming language discourages or prevents type errors.
'Terminology' 카테고리의 다른 글
[ Swift ] View Controller의 생명주기 ( Life - Cycle ) (0) | 2020.11.19 |
---|---|
[ Swift ] MVC ? MVVM ? (0) | 2020.10.26 |
[ Swift ] .self .Type .Protocol Self (0) | 2020.10.07 |
[ Swift ] instance / class / static (0) | 2020.10.07 |
( API , SDK ) vs. ( Framework vs. Library ) (2) | 2020.10.06 |