Generics power arrays and dictionaries, JSON decoding, Combine publishers and many other parts of Swift and iOS.
4.1 Getting started with generics
func replaceNilValues<T>(from array: [T?], with element: T) -> [T] {
array.compactMap {
$0 == nil ? element : $0
}
}
- compactMap 에 전달하는 transform 이라는 클로저의 타입:
(Element) **throws** -> ElementOfResult?)
- array 의 요소 하나씩을 가져와서 Optional 타입으로 반환한다.
- 반환 값중에 nil 은 무시되는 것이다.
- compactMap 의 시간 복잡도 : O(n + m)
- angle brackets (
‹›
) surround the function’s type parameters.
- A generic function receives type parameters as part of a function call, just like it receives regular function parameters.
- Once you define the type parameter inside the angle brackets, you can use it in the rest of the function’s declaration and even inside the function’s body.
- When you call this function, Swift replaces
T
with a concrete type that you’re calling the function with.
- This allows you to create a single function that works across all possible types, saving you from having to copy and paste functions.
- In a sense, generics are the opposite of protocols. Protocols allow you to call a function on multiple types where each type can specify its implementation of the function. Generics allow you to call a function on multiple types with the same
implementation of that function.
- it’s best to use a more descriptive type name that hints at its meaning to the reader. For example, instead of using single letters, you might use
Element
, Value
, Output
, etc.
- Swift allows you to add constraints to your generic types:
func max<T: Comparable>(lhs: T, rhs: T) -> T {
return lhs > rhs ? lhs : rhs
}
- You’re using
Comparable
as a generic constraint: a way to tell Swift which types are accepted for the generic type parameter.
Generic types
Protocols with associated types
Extending generics
Self and meta-types
4.2 Creating a generic networking library
- 실습 내용
- Protocol 로 작동되는 networking library 를 사용하는 클라이언트 앱
- 위 networking library 에 generics 를 적용하여 더 나은 API 를 만들어 본다.
- 코드 실제로 따라치면서 했음! → 완료