🍫 notion으로 보기
*본 포스트는 애플의 'A Swift Tour'를 바탕으로 작성되었으며, 공부하며 기록용으로 작성한 포스트이기 때문에 정확하지 않은 정보가 있을 수 있습니다!
** notion으로 작성한 문서를 임시로 올려둔 포스트이기 때문에 사진 링크의 오류와 문서의 형식 등으로 인해 보시기에 불편함이 있을 수 있습니다. (사진이 안나오거나 코드를 보기 불편한 점 등은 빠른 시일 내에 수정하도록 하겠습니다!)
Array와 Dictionary는 generic collection
generic 함수 또는 타입을 만들기 위해서 < > 대괄호angle brackets
안에 이름
을 쓴다.
func makeArray<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]() // Item타입으로 하는 배열
for _ in 0..<numberOfTimes {
result.append(item)
}
return result
}
makeArray(repeating: "knock", numberOfTimes: 4)
*Item
: 함수 makeArray가 호출될 때마다 타입이 결정된다!
functions, methods, classes, enumerations, structures 모두 generic타입으로 만들 수 있다.
// Reimplement the Swift standard library's optional type
enum OptionalValue<Wrapped> {
case none
case some(Wrapped)
}
var possibleInteger: OptionalValue<Int> = .none
possibleInteger = .some(100)
??? 무슨 말이지.. optional이니까 없거나(none) 있거나(some)..
where
요구사항의 리스트를 쓰기 전에 where을 써라. 예를 들어, 프로토콜을 심기 위해, 두개의 타입이 같도록하기 위해,클래스가 특정 슈퍼클래스를 가져야한다고 하기 위해
func anyCommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Bool
// Equatable: protocol, 값의 동일성을 비교할 수 있는 타입(Int, String, Double, Bool, Float, ...)
where T.Element: Equatable, T.Element == U.Element
{
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
func
funcName(_ paraName: paraType) → returnType {code
}
*<T: Equable>
= <T> ... where T: Equatable.
**experiment**
anyCommenElements(: :) 함수를 수정: 공통의 요소들을 가진 하나의 배열을 리턴하는 함수로
func CommonElements<T: Sequence, U: Sequence>(_ lhs: T, _ rhs: U) -> Array<T.Element>
where T.Element: Equatable, T.Element == U.Element
{
var commonArray = Array<T.Element>()
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
commonArray.append(lhsItem)
}
}
}
return commonArray
}