[英]How swift protocol Identifiable's @available working
協議 Identifiable 定義在 Swift > Misc 中的 iOS 13 以上可用
/// A class of types whose instances hold the value of an entity with stable identity.
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
public protocol Identifiable {
/// A type representing the stable identity of the entity associated with `self`.
associatedtype ID : Hashable
/// The stable identity of the entity associated with `self`.
var id: Self.ID { get }
}
@available(OSX 10.15, iOS 13, tvOS 13, watchOS 6, *)
extension Identifiable where Self : AnyObject {
/// The stable identity of the entity associated with `self`.
public var id: ObjectIdentifier { get }
}
但是,當我將部署目標設置為低於 11.0 的 iOS 13.0 ex) 時,不會發生任何編譯錯誤。
struct People: Identifiable {
var id: String {
return ""
}
}
let people = People()
print(people.id) // There are no compile error
問題是 Swift.Identifiable 的 @available 注釋如何工作?
即使您支持沒有該協議的 iOS 版本,您也可以將 object 聲明為符合協議,您將無法在這些版本中使用該協議一致性。
例如,您將無法做到這一點: people as? Identifiable
無需將其包裝在#available
塊中即可people as? Identifiable
。
您可以訪問people.id
而不會出現編譯器錯誤,因為它只是一個常規的String
屬性,即使沒有Identifiable
一致性,它仍然是您的結構的一部分。
如果您的 object 被聲明為 class 並且依賴於從協議一致性獲得的默認id
屬性,那么您將無法在沒有可用性檢查的情況下訪問id
屬性:
class People: Identifiable {
}
let people = People()
print(people.id) // compiler error outside of #available check
對於最新的 xcode 12.5 和 iOS 14.5 具有相同的問題。
它在 10.5.2 版本中有修復
只需更新您的 podfile: pod 'RealmSwift', '~> 10.5.2'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.