美文网首页
Swift | Protocol Oriented Progra

Swift | Protocol Oriented Progra

作者: 清無 | 来源:发表于2022-02-17 18:22 被阅读0次

Extending Protocols With Default Implementations

extension Bird {
  // Flyable birds can fly!
  var canFly: Bool { self is Flyable }
}

extension UnladenSwallow {
  var canFly: Bool {
    self != .unknown
  }
}

Extending Protocols

protocol Bird: CustomStringConvertible {
  var name: String { get }
  var canFly: Bool { get }
}

extension CustomStringConvertible where Self: Bird {
  var description: String {
    canFly ? "I can fly" : "Guess I'll just sit here :["
  }
}

Making It More Generic

// 1
func topSpeed<T: Sequence>(of racers: T) -> Double
    /*2*/ where T.Iterator.Element == Racer {
  // 3
  racers.max(by: { $0.speed < $1.speed })?.speed ?? 0.0
}

Making It More Swifty

extension Sequence where Iterator.Element == Racer {
  func topSpeed() -> Double {
    self.max(by: { $0.speed < $1.speed })?.speed ?? 0.0
  }
}

racers.topSpeed()        // 5100
racers[1...3].topSpeed() // 42

Init

protocol SomeProtocol {
    init()
}

class SomeSuperClass {
    init() {
        // initializer implementation goes here
    }
}

class SomeSubClass: SomeSuperClass, SomeProtocol {
    // "required" from SomeProtocol conformance; "override" from SomeSuperClass
    required override init() {
        // initializer implementation goes here
    }
}

A class-only protocol is marked by its inheritance from AnyObject

protocol DiceGame {
    var dice: Dice { get }
    func play()
}
protocol DiceGameDelegate: AnyObject {
    func gameDidStart(_ game: DiceGame)
    func game(_ game: DiceGame, didStartNewTurnWithDiceRoll diceRoll: Int)
    func gameDidEnd(_ game: DiceGame)
}

Protocol Composition

func wishHappyBirthday(to celebrator: Named & Aged) {
    print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}

The example also defines a wishHappyBirthday(to:) function. The type of the celebrator parameter is Named & Aged, which means “any type that conforms to both the Named and Aged protocols.”

Checking for Protocol Conformance

  • The is operator returns true if an instance conforms to a protocol and returns false if it doesn’t.
  • The as? version of the downcast operator returns an optional value of the protocol’s type, and this value is nil if the instance doesn’t conform to that protocol.
  • The as! version of the downcast operator forces the downcast to the protocol type and triggers a runtime error if the downcast doesn’t succeed.

Optional Protocol Requirements

@objc protocol CounterDataSource {
    @objc optional func increment(forCount count: Int) -> Int
    @objc optional var fixedIncrement: Int { get }
}

相关文章

网友评论

      本文标题:Swift | Protocol Oriented Progra

      本文链接:https://www.haomeiwen.com/subject/ykdllrtx.html