gpt4 book ai didi

swift - 当涉及 Optional(_SwiftValue) 时,如何检查 nil/NSNull/optional

转载 作者:可可西里 更新时间:2023-11-01 01:28:11 29 4
gpt4 key购买 nike

从 swift3 开始,我无法可靠地检测 nil/NSNull。在此代码段中,我得到了一个我不知道如何检测的 Optional(_SwiftValue) 值,而不是 nil

我试过了checking classForCoder没有运气。

其他地方有talk about id-as-Any causing this kind of problem

func testVotingMachine() {
let vote: String? = nil // Can be a string or nil
//let vote: String? = "president" // Can be a string or nil
var dict = [String: AnyObject?]()
dict["vote"] = vote as AnyObject?
let obj: AnyObject? = dict as AnyObject?

guard let dict2 = obj as? Dictionary<String, AnyObject?> else {
fatalError()
}

let value = dict2["vote"] as AnyObject?
let didVote = notNil(objectOrNil: value)
XCTAssertFalse(didVote) // BOOM! notNil() fails to detect nil
}

func notNil(objectOrNil: AnyObject?) -> Bool {
guard let object: AnyObject = objectOrNil else {
return false
}
if object is NSNull {
return false
}
//if object.classForCoder == NSNull.classForCoder() {
// return false
//}
// TODO: how to check for? Optional(_SwiftValue)
print("class for coder: \(object.classForCoder)")
return true
}

在将数据传递给 JSONSerialization.data() 之前,我需要对其进行清理。因此我需要检测 Optional(_SwiftValue)

最佳答案

String?Optional<String> 的简写.当它为零时,它实际上表示为 Optional<String>.none ,符合条件的是非零 AnyObject所以你的测试没有成功。

你可以这样修复它:

func notNil(objectOrNil: AnyObject?) -> Bool {
guard let object: AnyObject = objectOrNil,
object as! _OptionalNilComparisonType != AnyObject?.none else {
return false
}
if object is NSNull {
return false
}
//if object.classForCoder == NSNull.classForCoder() {
// return false
//}
// TODO: how to check for? Optional(_SwiftValue)
print("class for coder: \(object.classForCoder)")
return true
}

关于swift - 当涉及 Optional(_SwiftValue) 时,如何检查 nil/NSNull/optional,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40227565/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com