Providing a default value for an Optional in Swift?

后端 未结 4 1992
傲寒
傲寒 2020-11-29 17:57

The idiom for dealing with optionals in Swift seems excessively verbose, if all you want to do is provide a default value in the case where it\'s nil:

if let         


        
4条回答
  •  悲&欢浪女
    2020-11-29 18:50

    The following seems to work

    extension Optional {
        func getOrElse(defaultValue: T) -> T {
            if let value = self? {
                return value as T
            } else {
                return defaultValue
            }
        }
    }
    

    however the need to cast value as T is an ugly hack. Ideally, there should be a way to assert that T is the same as the type contained in the Optional. As it stands, type inferencing sets T based on the parameter given to getOrElse, and then fails at runtime if this does not match the Optional and the Optional is non-nil:

    let x: Int?
    
    let y = x.getOrElse(1.414) // y inferred as Double, assigned 1.414
    
    let a: Int? = 5
    
    let b: Double = a.getOrElse(3.14) // Runtime failure casting 5 to Double
    

提交回复
热议问题