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.