developer
developer

Reputation: 658

Check Non Optional value for nil

I'm creating a function in swift to check the if non optional value return nil. My aim is just to handle that exception and avoid app crash for unexpected nil values.

I have two variables in my class:

// My Class variables
var compulsoryValue: Any!

I dont want to check optionalValue as nil. The compiler is returning Optional.none or Optional.some enums instead of nil or some value.

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. Implicitly Unwrapped Optional is just throwing an error while it has a nil value.

How I can check that the value nil which was supposed as a non-optional value?

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

Upvotes: 0

Views: 598

Answers (1)

impression7vx
impression7vx

Reputation: 1863

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

Upvotes: 0

Related Questions