2

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.

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for that. The problem with this now is that a is optional and b is not. So according to the compiler, b will never be used since it is a non-optional.
For me this compiles and works perfectly without complaints. The case in the documentation is the same (a is optional, b is not). If your context is more complex please add additional information to your question.
It says: "Left side of nil coalescing operator '??' has a non-optional type '[[Bool]]', so the right side is never used". Is a optional for you and b not? I will add my exact figures in the post now.
Left side is a. If a is non-optional, the question makes no sense, you can just do var myVariable = a (because it will never be nil).
a is optional, b is not.
|
0
//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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.