V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
sl0000
V2EX  ›  Swift

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

  •  
  •   sl0000 · Apr 23, 2023 · 1894 views
    This topic created in 1111 days ago, the information mentioned may be changed or developed.
    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
       Apr 23, 2023
    [img][/img]
    nobodyknows
        2
    nobodyknows  
       Apr 23, 2023   ❤️ 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
       Apr 24, 2023
    @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  
       Apr 24, 2023
    也许可以利用子类对象可以 upcast 到父类对象这一点?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3461 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 55ms · UTC 10:41 · PVG 18:41 · LAX 03:41 · JFK 06:41
    ♥ Do have faith in what you're doing.