ぜのぜ

しりとりしようぜのぜのぜのぜ

73日目

日記

弊社は産業医の先生がいてたまに話せるんだけど,今日気になることがあったので診てもらった.会社員万歳.

今日書いたコード

protocol SomeDelegate: AnyObject {
    var some: String { get }
}

// Non-class type 'Kome' cannot conform to class protocol 'Some'
// struct Kome: Some {}

class Yome: SomeDelegate {
    var some = "somep"
}

class Hoge {
    var delegate: SomeDelegate?

    init() {}
}
Hoge()

初めて知ったこと

プロトコルAnyObjectを継承することで,そのプロトコルに準拠できるのはクラスだけになる.というかAnyObjectは全てのクラス*1が準拠しているプロトコルなのでAnyObjectを継承したプロトコルにクラス以外の型が準拠することはできない.*2*3

ドキュメントにはAnyObjectプロトコルだと書いてあるが,

The protocol to which all classes implicitly conform. https://developer.apple.com/documentation/swift/anyobject

structAnyObjectに準拠しようとするとAnyObjectプロトコルじゃないと怒られるのが今日のおもしろポイント.

struct Some: AnyObject {} // Inheritance from non-protocol type 'AnyObject'

ところで,この文の意味がわからない.weakにしなくても走るんですよね.

Marking the protocol as class-only lets the SnakesAndLadders class later in this chapter declare that its delegate must use a weak reference. https://docs.swift.org/swift-book/LanguageGuide/Protocols.html

*1:かつ全てのクラスのみ.多分

*2:という表現であっているか自信がない.Swiftの型の概念を把握しきれていないので

*3:そういえばアクターがいたな