Edited at

protocolでstaticなプロパティ

ただのメモです。

Swift 4.2


定義

protocol Hoge {

static var date: Date { get }
}

class StoredHoge: Hoge {
static var date = Date()
}

class ComputedHoge: Hoge {
static var date: Date {
return Date()
}
}


実行

let hoges: [Hoge.Type] = [StoredHoge.self, ComputedHoge.self]

print(Date())
//2019-05-09 02:07:28 +0000

hoges.forEach {
print($0, $0.date)
sleep(1)
}
//StoredHoge 2019-05-09 02:07:28 +0000
//ComputedHoge 2019-05-09 02:07:29 +0000

hoges.forEach {
print($0, $0.date)
sleep(1)
}
//StoredHoge 2019-05-09 02:07:28 +0000 //変わらない
//ComputedHoge 2019-05-09 02:07:31 +0000 //変わる