swift - 检查非可选值是否为零

标签 swift exception optional-variables optional-binding

我正在 swift 中创建一个函数来检查是否非可选值返回 nil。我的目标只是处理该异常并避免应用程序因意外的 nil 值而崩溃。

我的类中有两个变量:

// My Class variables
var compulsoryValue: Any!

我不想将optionalValue检查为nil。编译器返回 Optional.noneOptional.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/

相关文章:

Swift AnyClass 引用 Class 实例还是只是 Type?

c# - 多个可选参数调用函数

ios - Swift 选项 : What if i need to change an non - optional type to optional

swift - Swift 中的枚举变量?

ios - 为什么 UIScrollView 在显示键盘时不滚动?

ios - Facebook iOS SDK 和 Swift : how to get user's hometown?

macos - 错误 : 'uncaught_exceptions' is unavailable: introduced in macOS 10. 12

Android 无法从 Activity 访问 textView 组件

java - <init> 在 Java 异常中表示什么?

swift - 对 swift 中的选项有点困惑