简体   繁体   中英

Python “or” equivalent in Swift?

Due to Swift cool behaviors I was looking for an or equivalent in Swift.

Something like this:

variable = value or default

I coded mine :

func |<T>(a:T?, b:T) -> T {
    if let a = a {
        return a
    }
    return b
}

But I was wondering if any default implementation of this already exists in Swift?

Edit: Thanks to answers I found the reference in the Swift book:

Nil Coalescing Operator

The nil coalescing operator ( a ?? b ) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a .

The nil coalescing operator is shorthand for the code below:

  a != nil ? a! : b 

The code above uses the ternary conditional operator and forced unwrapping ( a! ) to access the value wrapped inside a when a is not nil, and to return b otherwise. The nil coalescing operator provides a more elegant way to encapsulate this conditional checking and unwrapping in a concise and readable form. ( source )

Use ?? :

var optional:String?
var defaultValue:String = "VALUE"

var myString:String = optional ?? defaultValue

print(myString)

您可以使用nil合并运算符

let variable = optional ?? default

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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