Shortcut for assignment if nil in Swift?

if x == nil { x = y } 

I know that the above statement can be rewritten as:

 x = x ?? y 

But x ??= y not accepted by the compiler. Is there a shorthand not to repeat x ?

+7
source share
3 answers

Check this out, put the following in the global code space (perhaps in your Extensions.swift). This creates a custom operator that you can use throughout the project.

Swift 2

 infix operator ??= {} func ??= <T>(inout left: T?, right: T) { left = left ?? right } 

Swift 3

 infix operator ??= func ??= <T>(left: inout T?, right: T) { left = left ?? right } 

Using:

 var foo: String? = nil var bar = "Bar" foo ??= bar print("Foo: \(bar)") 

Hope this helps :)

+8
source

This code works in the playground:

 var x: Int? = nil let y = 5 x = x ?? y // x becomes 5 

and

 var x: Int? = 6 let y = 5 x = x ?? y // x stays 6 

By the way, some verification options for nil:

 if x != nil { // classic } if x != .None { // nil in Swift is enum with value .None } if let _x = x { // if you need it value } if let _ = x { // if you don't need it value } 

UPD: code for the project - copy and run it:

 var x: Int? = nil let y = 5 x = x ?? y print (x) x = 7 x = x ?? y print (x) 
+2
source

Laffens answer is great. However, this is not entirely equivalent to x = x?? y x = x?? y x = x?? y x = x?? y as the right part is always evaluated with their definition ??= in contrast to the standard ?? operator.

If you want to have this behavior, @autoclosure here to help:

 infix operator ??= func ??=<T>(left: inout T?, right: @autoclosure () -> T) { left = left ?? right() } 
0
source

Source: https://habr.com/ru/post/1237306/


All Articles