Why create “Implicitly Unwrapped Optionals”, since that implies you know there's a value?

前端 未结 10 1694
深忆病人
深忆病人 2020-11-22 07:30

Why would you create a \"Implicitly Unwrapped Optional\" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create a

10条回答
  •  醉酒成梦
    2020-11-22 08:02

    If you know for sure, a value return from an optional instead of nil, Implicitly Unwrapped Optionals use to directly catch those values from optionals and non optionals can't.

    //Optional string with a value
    let optionalString: String? = "This is an optional String"
    
    //Declaration of an Implicitly Unwrapped Optional String
    let implicitlyUnwrappedOptionalString: String!
    
    //Declaration of a non Optional String
    let nonOptionalString: String
    
    //Here you can catch the value of an optional
    implicitlyUnwrappedOptionalString = optionalString
    
    //Here you can't catch the value of an optional and this will cause an error
    nonOptionalString = optionalString
    

    So this is the difference between use of

    let someString : String! and let someString : String

提交回复
热议问题