본문 바로가기
IT/swift

100 days of SwiftUI - Day13, Day14, Day15

by 가능성1g 2024. 11. 15.
반응형

protocol 과 extension

 

protocol 은 java 의 interface 와 비슷 extension 은 c#의 partial class 같이 일부를 재 정가능한데 class 가 아닌 struct 와 protocol 을 추가 지정이 가능함. 그래서 extension 을 이용해서 c++의 연산자 오버라이딩 이 구현 가능함 . 물론 기존 타입(String, Array) 등도 확장가능함. 기존타입들이 struct이기 때문에 가능 함

 

protocol Person {
    var name: String { get }
    func sayHello()
}

extension Person {
    func sayHello() {
        print("Hi, I'm \(name)")
    }
}

struct Employee: Person {
    let name: String
}

let taylor = Employee(name: "Taylor Swift")
taylor.sayHello()

프로토콜 확장 예제

프로토콜에서 변수는 get/set 을 지정하고 함수는 구현 불가함

하지만 extension으로 구현할 수 있으며, 이는 struct에서 protocol을 받으면 이어받아짐!

 

쳌포8

"""
 make a protocol that describes a building, adding various properties and methods, then create two structs, House and Office, that conform to it. Your protocol should require the following:

A property storing how many rooms it has.
A property storing the cost as an integer (e.g. 500,000 for a building costing $500,000.)
A property storing the name of the estate agent responsible for selling the building.
A method for printing the sales summary of the building, describing what it is along with its other properties.
"""
protocol Building {
    var roomsCount: Int { get set }
    var cost:Int { get set}
    var estateAgentName: String { get set }
    func describe()
}

extension Building {
    func describe() {
        print("\(estateAgentName) \(roomsCount) \(cost)")
    }
}

struct House: Building {
    var roomsCount: Int
    var cost:Int
    var estateAgentName:String
}

struct Office: Building {
    var roomsCount: Int
    var cost:Int
    var estateAgentName:String
    
    func describe() {
        print("I'm Office")
    }
}

let myHouse = House(roomsCount: 4, cost: 100_000_000, estateAgentName: "Han")
myHouse.describe()

let myOffice = Office(roomsCount: 2, cost: 100_000, estateAgentName: "KJB")
myOffice.describe()

protocol 에서 변수의 get/set 에 따라 get 만 -> struct 에서 let 으로 선언해야 한다!  get/set struct에서 var 로 선언해야 한다!

가 된다..

 

근데 class 를 나두고 굳이 extension 의 키워드를 이용해 struct의 protocol을 이용한 확장을 만든거지...? 아직은 공감이 안되는군.

 

optional => ?, ??, try?, if let 구문, guard 구문

kotlin 에서 많이 봤던 구문이라 간단하게 말로 요약

nil ( 널을 swift 에서는 nil 로 ) 을 포함하는 타입일때 String?으로 선언 가능

접근할때도, 해당 객체명? 으로 표기해서 nil이 포함된 변수, 객체등에 접근이 가능함 

그리고 nil 인 경우의 에러 방지를 위해 if let aaa=bbb  { } 로 하면 nil 인 경우 실행 안되거나 반대로  guard let aaa=bbb else {} nil 인 경우 예외 처리 가능

try? 를 이용해 함수인 경우 예외가 던저지는 경우를 처리 할 수 있음 

??를 이용해 값대체가 가능

let user = (try? getUser(id: 23)) ?? "Anonymous"
print(user)

getUser했을때 exception 이 throw 되면 Anonymous 로 찍기

 

"""
write a function that accepts an optional array of integers, and returns one randomly. If the array is missing or empty, return a random number in the range 1 through 100.
"""
func foo ( num: [Int] ) -> Int {
    return num.randomElement() ?? Int.random(in: 1...100)
}

print(foo(num: []))
print(foo(num: [1,2,3]))

 

Day15는 swift 리뷰!

반응형