LoginSignup
0
1

More than 3 years have passed since last update.

protocolでstaticな関数

Posted at

ただのメモです。
Swift 4だか5だか。

定義

protocol P {
    static func staticFunc() -> String
}
extension P {
    static func staticFunc() -> String {return "default"}
}
class A: P {
    static func staticFunc() -> String {return String(describing: self)}
}
class B: P {}
class C: A {}
class D    {}
//class E: A {
//  static override func staticFunc() -> String {return "hogehoge"}
//}
//error: cannot override static method

実行

[A.self, B.self, C.self, D.self].forEach {
    if let type = $0 as? P.Type {
        print("\(type): \(type.staticFunc())")
    }
}
//A: A
//B: default
//C: C
  • DPに準拠していないので呼び出されない。
  • overrideは出来ない。
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1