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 的答案
![]() | 1 sl0000 OP |
2 nobodyknows 2023-04-23 22:36:45 +08:00 ![]() ```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))") } ``` |
![]() | 3 sl0000 OP @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") } } } } |
![]() | 4 agagega 2023-04-24 23:40:30 +08:00 也许可以利用子类对象可以 upcast 到父类对象这一点? |