可识别的协议如何快速可用的工作方式

问题描述 投票:2回答:1

可识别协议定义在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注释如何工作?

swift protocols
1个回答
1
投票

即使您支持不具有该协议的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
© www.soinside.com 2019 - 2024. All rights reserved.