extension

extension 은 StoreProperties 사용 불가 Computed Properties 로 사용


Protocol

특정한 조건을 강제하고 싶을때 사용

Protocol 은 값은 지정할 수 없다, 어떤스타일을 사용할건지 규격 지정 (타입, get, set)

프로토콜이란?
특정 역할을 하기 위한 메소드, 프로퍼티, 기타 요구사항 등의 청사진

프로토콜의 사용
구조체, 클래스, 열거형은 프로토콜을 채택해서 특정 기능을 실행하기 위한 프로토콜의 요구사항을 실제로 구현할 수 있다.
프로토콜은 정의를 하고 제시를 할 뿐 스스로 기능을 구현하지는 않는다. (조건만 정의)
하나의 타입으로 사용되기 때문에 아래와 같이 타입 사용이 허용되는 모든 곳에 프로토콜을 사용할 수 있다.

구조체, 클래스, 열거형 등에서 프로토콜을 채택하려면 타입 이름 뒤에 콜론“:”을 붙여준 후 채택할 프로토콜 이름을 쉼표“,”로 구분하여 명시해준다.
(SubClass의 경우 SuperClass를 가장 앞에 명시한다.)


Higher_Order_Func

// map

var array = [1, 2, 4, 3]
var tempArray = array.map{ $0 * 10 }
print(tempArray)

// compact map

let stringArray = ["lee", "june", "kim"]
let someArray: [Any] = [1, 2, 3, 4, "Bob", "Col"]
let tempSomeArray = someArray.compactMap{ $0 as? Int }
let tempSomeArray2 = someArray.map{ $0 as? Int }

// map 과 compactMap 차이점, Int형으로 타입캐스팅이 되는것들은 Optional로 나오고 아닌것들은 nil로 나온다
print(tempSomeArray)
// [1, 2, 3, 4]
print(tempSomeArray2)
// [Optional(1), Optional(2), Optional(3), Optional(4), nil, nil]

// filter
let over3 = array.filter{ $0 > 3}
print(over3)


// reduce
let reduceResult = array.reduce(100) { $0 + $1 }
print(reduceResult)

let reduceResultString = stringArray.reduce("") { $0 + $1 }
print(reduceResultString)


// sort (해당되는 값을 변경한다)
// sorted (해당되는 값을 변경하지 않는다)

array.sort()
// [1, 2, 3, 4]
array.sort(by: > )
// [4, 3, 2, 1]
array.sort(by: <)
//[1, 2, 3, 4]

'swift > 잡다함' 카테고리의 다른 글

filePrivate, private 차이  (0) 2021.06.24
Struct VS Class  (0) 2021.06.16
기본 클로저 사용  (0) 2021.06.07
ARC (weak, unowned)  (0) 2021.06.01
mutating  (0) 2021.02.17

+ Recent posts