简体   繁体   English

检查Non Optional值是否为nil

[英]Check Non Optional value for nil

I'm creating a function in swift to check the if non optional value return nil. 我正在快速创建一个函数来检查是否非可选值返回nil。 My aim is just to handle that exception and avoid app crash for unexpected nil values. 我的目的只是为了处理该异常,并避免因意外的nil值而导致应用程序崩溃。

I have two variables in my class: 我班上有两个变量:

// My Class variables
var compulsoryValue: Any!

I dont want to check optionalValue as nil. 我不想将optionalValue检查为nil。 The compiler is returning Optional.none or Optional.some enums instead of nil or some value. 编译器返回Optional.noneOptional.some枚举,而不是nil或某些值。

My problem: 我的问题:

I'm facing the problem that I am not able to check if this value is empty or not. 我面临的问题是我无法检查此值是否为空。 As for empty the compiler returning none while for a value it is return some as defined in Swift Optional Enum . 至于空,编译器不返回none value ,而返回value则是Swift Optional Enum定义的。 Implicitly Unwrapped Optional is just throwing an error while it has a nil value. Implicitly Unwrapped Optional仅在其值为nil时抛出错误。

How I can check that the value nil which was supposed as a non-optional value? 我如何检查值nil(该值应为非可选值)?

Update# 1: 更新#1:

My code: 我的代码:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM