如果涉及Optional(_SwiftValue),如何检查nil / NSNull / optional

时间:2016-10-24 21:06:45

标签: swift swift3

从swift3开始我无法可靠地检测到nil / NSNull。在此代码段中,我得到的nil值不是Optional(_SwiftValue),而是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 } ,我不知道如何检测。

我没有运气就试过checking classForCoder

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

JSONSerialization.data()

我需要在将数据传递给Optional(_SwiftValue)之前对其进行清理。因此,我需要检测//method for runtime testing for getNthPopular() // Average time for getNthPopular(); Trends tr = new StudentTrends(); //...more code int n = tr.numEntries(); //number of pairs startTime = System.nanoTime(); for (int i = 0; i < n; i++) //get the Nth popular string term in the textfile tr.getNthPopular(i); endTime = System.nanoTime(); double test3 = (double)((endTime - startTime)/1000000.0)/(double)n; System.out.println("Test 3: " + test3 + " milliseconds /getNthPopular"); //................runtime testing method ends...................

1 个答案:

答案 0 :(得分:2)

RewriteString?的简写。当它为零时,它实际上表示为Optional<String>,其符合条件为非零Optional<String>.none,因此您的测试不起作用。

你可以这样解决:

AnyObject