πŸ‘©πŸ»‍πŸ’» iOSun
article thumbnail

ν”„λ‘œν† μ½œ (Protocols)

  • λ”°λΌμ•Όν•˜λŠ” μš”κ΅¬ 사항을 μ •μ˜ν•œλ‹€.
class SomeClass: SomeSuperclass, FirstProtocol, AnotherProtocol {
    // class definition goes here
}
  • μž‘μ„± μˆœμ„œ : λΆ€λͺ¨ν΄λž˜μŠ€ λ¨Όμ € μž‘μ„±ν•˜κ³  κ·Έ λ‹€μŒμ— ν”„λ‘œν† μ½œμ„ μ±„νƒν•œλ‹€.
protocol SomeProtocol {
    var mustBeSettable: Int { get set }
    var doesNotNeedToBeSettable: Int { get }
}
  • 각 ν”„λ‘œνΌν‹°κ°€ gettable 인지 gettableκ³Ό settable 인지 μ§€μ •ν•΄μ€˜μ•Ό 함

 

mutating λ©”μ†Œλ“œ μš”κ΅¬μ‚¬ν•­

protocol Togglable {
    mutating func toggle()
}

enum OnOffSwitch: Togglable {
    case off, on
    mutating func toggle() { }
}

class Light: Togglable {
    func toggle() { }
}
  • μ—΄κ±°ν˜•μ΄λ‚˜ ꡬ쑰체가 ν”„λ‘œν† μ½œμ„ 채택 → mutating ν‚€μ›Œλ“œ μž‘μ„±ν•¨
  • ν΄λž˜μŠ€κ°€ ν”„λ‘œν† μ½œ 채택 → mutating ν‚€μ›Œλ“œ μž‘μ„±ν•  ν•„μš”μ—†μŒ

 

protocol SomeProtocol {
    init(someParameter: Int)
}

final class SomeClass: SomeProtocol {
    required init(someParameter: Int) {
        // initializer implementation goes here
    }
}
  • xcodeμ—μ„œ λ”°λ‘œ μ›Œλ‹μ€ μ•ˆλ– λ„ λ§Œμ•½ finalν‚€μ›Œλ“œκ°€ λΆ™μœΌλ©΄ required λΆ™μ΄λŠ”κ²Œ μ˜λ―Έμ—†μŒ (상속될 일이 μ—†κΈ°λ•Œλ¬Έμ— μš”κ΅¬ μƒμ„±μžλ₯Ό κ΅¬ν˜„ν•  일도 μ—†λ‹€)

 

protocol InheritingProtocol: SomeProtocol, AnotherProtocol {
    // protocol definition goes here
}
  • ν”„λ‘œμ½”μ½œμ΄ ν”„λ‘œν† μ½œμ„ 상속할 수 있음

 

protocol SomeClassOnlyProtocol: AnyObject, SomeInheritedProtocol {
    // class-only protocol definition goes here
}
  • AnyObject ν”„λ‘œν† μ½œ μ±„νƒν•˜λ©΄ 클래슀 μ „μš© ν”„λ‘œν† μ½œ λ§Œλ“€ 수 있음

 

ν”„λ‘œν† μ½œ ν˜Όν•©

protocol Named {
    var name: String { get }
}
protocol Aged {
    var age: Int { get }
}
struct Person: Named, Aged {
    var name: String
    var age: Int
}
func wishHappyBirthday(to celebrator: Named & Aged) {
    print("Happy birthday, \\(celebrator.name), you're \\(celebrator.age)!")
}
let birthdayPerson = Person(name: "Malcolm", age: 21)
wishHappyBirthday(to: birthdayPerson)
  • & ν‚€μ›Œλ“œ (ex Named & Aged) (μ—¬λŸ¬κ°œλ„ κ°€λŠ₯)
  • & ν‚€μ›Œλ“œλ‘œ 묢인 ν”„λ‘œν† μ½œμ„ μ±„νƒν•œ νƒ€μž…μ„ λ‚˜νƒ€λƒ„

 

Optional Protocol μš”κ΅¬μ‚¬ν•­

@objc protocol CounterDataSource {
    @objc optional func increment(forCount count: Int) -> Int
    @objc optional var fixedIncrement: Int { get }
}
  • ν”„λ‘œν† μ½œ μ•ˆμ— μ„ μ–Έλ˜μ–΄ μžˆλŠ” ν”„λ‘œνΌν‹° / λ©”μ„œλ“œλŠ” λͺ¨λ‘ required 즉, ν•„μˆ˜μ μΈ 것
  • κΌ­ κ΅¬ν˜„ν•˜μ§€ μ•Šμ•„λ„ λ˜λŠ” ν”„λ‘œνΌν‹°λ‚˜ λ©”μ†Œλ“œλ₯Ό λ§Œλ“€κ³  싢을 λ•Œ μ˜΅μ…”λ„ ν”„λ‘œν† μ½œ μ‚¬μš©
  • ν”„λ‘œν† μ½œκ³Ό μ˜΅μ…”λ„ μš”κ΅¬μ‚¬ν•­μ€ λͺ¨λ‘ @objc μ†μ„±μœΌλ‘œ ν‘œμ‹œλ˜μ–΄μ•Όν•œλ‹€.
    • μ˜΅μ…”λ„ ν”„λ‘œν† μ½œμ€ 클래슀만 μ‚¬μš© (ꡬ쑰체, μ—΄κ±°ν˜• x)
    • Objective-Cμ—μ„œ ν”„λ‘œν† μ½œμ€ μ˜€λ‘œμ§€ "클래슀 μ „μš©"μ—μ„œλ§Œ μ±„νƒν•˜κΈ° λ•Œλ¬Έ
profile

πŸ‘©πŸ»‍πŸ’» iOSun

@iosun

ν¬μŠ€νŒ…μ΄ μ’‹μ•˜λ‹€λ©΄ "μ’‹μ•„μš”β€οΈ" λ˜λŠ” "κ΅¬λ…πŸ‘πŸ»" ν•΄μ£Όμ„Έμš”!

profile on loading

Loading...