0

I'm playing with as! and as? in Swift, and according to Apple docs:

The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action.

And here's my code in playground:

let arr:[Any] = [1];

let a = arr.first;
print("a is \(a)");//a is Optional(1)

let x = a as! Int!;
print("x is \(x)");//x is Optional(1)

let y: Int! = a as! Int!;
print("y is \(y)");//y is Optional(1)

var z = 1 + y;// z = 2
var t = 1 + x;// Compile error

The last 2 lines really confused me because x and y are supposed to have the type of (Int!) (according to Apple's doc above). But here only y could be used in the assignment clause (in z), yet x couldn't (in t).

Can someone please explain this?

Please excuse me if this question's been asked somewhere else on SO. Also please don't mind my semicolon(;), it's just a habit so I won't mess up while switching between Objc and Swift :). Edited: Remove the ":" that shouldn't be there. Thanks to Hamish

hoang Cap
  • 704
  • 6
  • 18
  • 2
    Compare [Implicitly unwrapped optional assign in Xcode 8](http://stackoverflow.com/q/39633481/2976878) – `x` is of strong optional type `Int?`, not `Int!`. – Hamish Apr 21 '17 at 19:18
  • Spent 15 minutes writing an answer. Thanks for closing it right before I could press the done button. Not. – Brandon A Apr 21 '17 at 19:25
  • @BrandonA Dang, I'm sorry :/ Usually you can still submit ~5 mins after the question being closed (server gives you a bit of leeway). Was there anything in your answer that wasn't covered in the linked Q&A? – Hamish Apr 21 '17 at 19:28
  • @Hamish It's all good in the neighborhood brother. – Brandon A Apr 21 '17 at 19:30

0 Answers0