简体   繁体   中英

How swift protocol Identifiable's @available working

protocol Identifiable is defined available above iOS 13 in Swift > Misc

/// 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 }
}

But when I setup deployment target to under iOS 13.0 ex) below 11.0 there are not any compile error occur.

struct People: Identifiable {
    var id: String {
        return ""
    }
}

let people = People()
print(people.id) // There are no compile error

Question is How Swift.Identifiable's @available annotation working?

You can declare an object as conforming to a protocol even if you support iOS versions that don't have that protocol, you just won't be able to use that protocol conformance in those versions.

For example, you would not be able to do this: people as? Identifiable people as? Identifiable without wrapping it in a #available block.

You can access people.id without a compiler error because it's just a regular String property that is still part of your struct even without the Identifiable conformance.

If your object was declared as a class and was relying on the default id property that it gets from the protocol conformance then you wouldn't be able to access the id property without an availability check:

class People: Identifiable {

}

let people = People()
print(people.id) // compiler error outside of #available check

For the latest xcode 12.5 and iOS 14.5 has the same issue.

It has a fix in 10.5.2 version

just update your podfile with: pod 'RealmSwift', '~> 10.5.2'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM