Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Any型をprotocolにキャストする時に 気をつけた方がいい話

Any型をprotocolにキャストする時に 気をつけた方がいい話

PKPK-Carnage

May 21, 2019
Tweet

More Decks by PKPK-Carnage

Other Decks in Programming

Transcript

  1. About me • iOSྺ2೥ͪΐͬͱ • Qiita → @PKPK-Carnage • Github

    → PKPK-Carnage • Twitter → @PKPK-Carnage
  2. ྫɿNotification 6 class HogeClass { func postNotification() { // DogΛૹΔ

    NotificationCenter.default.post( name: .init("Animal"), object: Dog() ) } }
  3. ྫɿNotification 7 class FugaClass { init() { NotificationCenter.default.addObserver( self, selector:

    #selector(self.didReceivedNotification(_:)), name: .init("Animal"), object: nil ) } @objc func didReceivedNotification(_ notification: Notification) { } }
  4. ྫɿNotification 8 @objc func didReceivedNotification(_ notification: Notification) { // notification.objectͷத਎Λग़ྗ͢Δ

    print("\(String(describing: notification.object))") // notification.objectΛAnimal(Protocol)ʹΩϟετͨ͠ޙͷத਎Λग़ྗ͢Δ let animal = notification.object as? Animal print("\(String(describing: animal))") } Optional(__lldb_expr_11.Dog()) nil
  5. 9

  6. ࣮ࡍʹ΍ͬͯΈͨ 12 @objc func didReceivedNotification(_ notification: Notification) { // notification.objectͷத਎Λग़ྗ͢Δ

    print("\(String(describing: notification.object))") // notification.objectΛAnimal(Protocol)ʹΩϟετͨ͠ޙͷத਎Λग़ྗ͢Δ let animal = notification.object as? Animal print("\(String(describing: animal))") }
  7. ࣮ࡍʹ΍ͬͯΈͨ 13 @objc func didReceivedNotification(_ notification: Notification) { // notification.objectͷத਎Λग़ྗ͢Δ

    print("\(String(describing: notification.object))") // notification.objectΛAnimal(Protocol)ʹΩϟετͨ͠ޙͷத਎Λग़ྗ͢Δ let animal = (notification.object as AnyObject) as? Animal print("\(String(describing: animal))") }
  8. ࣮ࡍʹ΍ͬͯΈͨ 14 Optional(__lldb_expr_11.Dog()) Optional(__lldb_expr_11.Dog()) @objc func didReceivedNotification(_ notification: Notification) {

    // notification.objectͷத਎Λग़ྗ͢Δ print("\(String(describing: notification.object))") // notification.objectΛAnimal(Protocol)ʹΩϟετͨ͠ޙͷத਎Λग़ྗ͢Δ let animal = (notification.object as AnyObject) as? Animal print("\(String(describing: animal))") }
  9. 15