我正在 swift 中创建一个函数来检查是否非可选值返回 nil。我的目标只是处理该异常并避免应用程序因意外的 nil 值而崩溃。
我的类中有两个变量:
// My Class variables
var compulsoryValue: Any!
我不想将optionalValue
检查为nil。编译器返回 Optional.none
或 Optional.some
枚举,而不是 nil
或某个值。
我的问题:
我面临的问题是无法检查该值是否为空。对于空编译器返回 none
,而对于 value
则返回一些 Swift
Optional Enum
中定义的内容。
Implicitly UnwrappedOptional
只是在具有 nil
值时抛出错误。
如何检查值 nil 是否被认为是非可选值?
更新#1:
我的代码:
class myClass {
var compulsoryValue: Any!
init() {
if type(of: compulsoryValue) != Optional<Any>.self {
// Here I want to check if compulsoryValue is nil so I want to throw an exception
print("this is not optional: ", compulsoryValue)
}
}
}
_ = myClass()
最佳答案
class myClass {
var compulsoryValue: Any!
var optionalValue: Any?
init() {
let variabless = [compulsoryValue, optionalValue]
for (_, v) in variabless.enumerated() {
if(v != nil) { //Or v == nil
// Here I want to check if v is nil so I want to throw an exception
print("this is not optional: ", v)
}
}
}
}
_ = myClass()
关于swift - 检查非可选值是否为零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50952161/