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

2023-04-23 20:07:55 +08:00
 sl0000
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

1149 次点击
所在节点    Swift
4 条回复
sl0000
2023-04-23 20:15:03 +08:00
[img][/img]
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))")
}
```
sl0000
2023-04-24 13:10:08 +08:00
@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
2023-04-24 23:40:30 +08:00
也许可以利用子类对象可以 upcast 到父类对象这一点?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/934873

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX