V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
sl0000
V2EX  ›  Swift

Swift 的 Optional 如何比较包装类型的关系呢?

  •  
  •   sl0000 · 340 天前 · 1081 次点击
    这是一个创建于 340 天前的主题,其中的信息可能已经有所发展或是发生改变。
    var a: Int? = nil
    print("\(type(of: a))")
    print("\(a is String?)")
    
    var b: Int? = 1
    print("\(type(of: b))")
    print("\(b is String?)")
    
    /*
    output::
    Optional<Int>
    true
    Optional<Int>
    false
     */
    

    下面是 GPT 的答案

    Imgur

    sl0000
        1
    sl0000  
    OP
       340 天前
    [img][/img]
    nobodyknows
        2
    nobodyknows  
       340 天前   ❤️ 1
    ```swift
    func isTypeEqual<T1, T2>(_ v: T1, _ t: T2.Type) -> Bool {
    return ObjectIdentifier(T1.self) == ObjectIdentifier(T2.self)
    }

    func test() {
    let a: Int? = nil
    print("\(isTypeEqual(a, Optional<Int>.self))")
    print("\(isTypeEqual(a, Optional<String>.self))")
    }
    ```
    sl0000
        3
    sl0000  
    OP
       340 天前
    @nobodyknows 感谢,可能是我描述不够清晰,我其实是要做 optional<subclass>与 optional<class>的继承关系比较,而不是==

    protocol OptionalProtocol {
    static func wrappedType() -> Any.Type
    func wrappedType() -> Any.Type
    }
    extension Optional: OptionalProtocol {
    static func wrappedType() -> Any.Type {
    return Wrapped.self
    }
    func wrappedType() -> Any.Type {
    return Wrapped.self
    }
    }


    class KeyValueCoding {
    init() {
    defaultKeyValue()
    }

    func defaultKeyValue() {
    // let userDefault = UserDefaults.standard
    let classPath = String(describing: self)
    let mirror = Mirror(reflecting: self)
    for child in mirror.children {
    guard let label = child.label else { continue }
    let fullLabel = classPath + "." + label
    let type = type(of: child.value)
    let value = child.value
    print("\(fullLabel) \(type)")
    if let wrappedType = (type as? OptionalProtocol.Type)?.wrappedType() {
    print("optional \(wrappedType)")
    } else {
    print("not optional")
    }
    }
    }
    }
    agagega
        4
    agagega  
       339 天前
    也许可以利用子类对象可以 upcast 到父类对象这一点?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5292 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 05:56 · PVG 13:56 · LAX 22:56 · JFK 01:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.