How to use shift operator with implicit/forced unwrapping in Swift

61 views Asked by At

I have been trying to use shift operator and unwrapping in a piece of code, as I'm learning Swift (FYI just a beginner), so I'm trying out multiple things, but I'm stuck with this operator. Looking at different threads about shift operators, I came to a conclusion that,, I may have to overload my operands and then use them accordingly.

My piece of code :

var p : Int! 
p = 24 >> 2;
if let msg = p{ print (msg); } 
else { print("abcd"); }

Please, help! And also advice if my thinking is correct or not.

All I want to achieve is that both may work together.. If there is any way applicable... xD

1

There are 1 answers

2
Joakim Danielson On

If I understand the question correctly this is a misunderstanding and has nothing to do specifically with using optionals and shift operators together

If you want to use the syntax if let x = y { then this is only allowed if y is declared as optional since the code is pointless if y is never nil because then you can safely use y directly.

When it comes to shift operators then neither value can be optional as far as I know so your example is a little contrived.

var y: Int?

if someCondition {
    y = 42
}

if let x = y {
   doStuff(x)
}  else {
    print("y was never set")
}

or unwrap with default value

var y: Int?

let x = (y ?? 0) + 42