J.Treutlein
J.Treutlein

Reputation: 983

Swift: Setting variables if not equalling nil

I'm using Swift and I'm wondering how to achieve this in 1 line of code:

If a != nil, myVariable = a

else if a == nil, myVariable = b

I need to do this so it fits with

var myVariable = a {
    didSet{
        //Do something
    }
}

Is there a way to do this in 1 line so I don't have to change it elsewhere and trigger the didSet{}?

Something like this:

if var myVariable = a 
else myVariable = b {
    didSet{
        //Do something
    }
}

Or...

var if a != nil {myVariable = a}
else {myVariable = b} {
    didSet{
        //Do something
    }
}

I know this may take some time to realise what I mean, I tried my best to explain it.

EDIT ---> The compiler says:

Left side of nil coalescing operator '??' has a non-optional type '[[Bool]]', so the right side is never used

and

Treating a forced downcast to '[[Bool]]' as optional will never produce 'nil'

This is what it looks like using a coalescing operator:

var purchased =
UserDefaults.standard.array(forKey: "purchased") as! [[Bool]] ?? 
[[true, false], [true, false], [true, false], [true, false], [true, false]] { //a is left, b is right
    didSet {
        //Do something
    }
}

Any ideas would be greatly appreciated. Thank you.

Upvotes: 2

Views: 989

Answers (2)

Gerriet
Gerriet

Reputation: 1350

How about

var myVariable = a ?? b

This sets myVariable to a except for the case when a == nil, then it sets myVariable to b. didSet would be called once with the respective value. It is called a "nil coalescing operator".

Your edited questions shows that a in your case cannot be nil because you force unwrap the array (with as!). Instead you should conditionally unwrap it (as?), so that your code can check for nil and use the hard-coded default instead.

Upvotes: 5

impression7vx
impression7vx

Reputation: 1863

//Sets my variable to a if a != nil, else b.
var myVaraiable = (a != nil ? a : b)

Since a is optional and b is not, it would be more like

var myVariable = (a != nil ? a! : b)

Upvotes: 0

Related Questions