可识别协议定义在iOS 13以上版本的Swift>其他
/// 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 }
}
但是当我将部署目标设置为低于iOS 13.0 ex时)低于11.0没有任何编译错误发生。
struct People: Identifiable {
var id: String {
return ""
}
}
let people = People()
print(people.id) // There are no compile error
问题:Swift.Identifiable的@available注释如何工作?
即使您支持不具有该协议的iOS版本,也可以将对象声明为符合该协议,否则您将无法在那些版本中使用该协议一致性。
例如,如果不将其包装在people as? Identifiable
块中,您将无法执行此操作:#available
。>
您可以在没有编译器错误的情况下访问people.id
,因为它只是一个常规的String
属性,即使没有Identifiable
一致性,它仍然是结构的一部分。
如果您的对象被声明为类,并且依赖于它从协议一致性中获取的默认id
属性,那么在没有可用性检查的情况下,您将无法访问id
属性:
class People: Identifiable {
}
let people = People()
print(people.id) // compiler error outside of #available check