0

I experienced a strange response from xcode 9.3 running swift 4.1 while running this code:

let old = "not an int"

let new: Int! = Int(old) ?? 2

print(new)

print(new!)

Response is some(2) and 2 (with forced unwrapping) (check image below).

Where is this some coming from? (please explain or provide reference to read more about some)

enter image description here

Nabeel Khan
  • 3,715
  • 2
  • 24
  • 37

4 Answers4

1

some is like optional is added to optional values when printing them it's new in swift 4.1

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
1

When you declared a variable marking it as unwrapped means compiler will think there is always some value instead of Optional which means the value can be nil.

some indicates there is always a value but its not unwrapped yet.

0

let new: Int! is an Optional<Int>, that just happens to be implicitly unwrapped everywhere its used where an Int is expected.

print takes an Any.... Optional<Int> is just as much of an Any as Int is. There's no reason for implicitly unwrapping to be done, and so it isn't.

Alexander
  • 59,041
  • 12
  • 98
  • 151
  • Unfortunately it's slightly more nuanced than that; in Swift 4.1, `ImplicitlyUnwrappedOptional` is still a type that exists, and is used by the compiler. The `some(2)` is its `description`, as given by Swift's default reflection mechanism. `Optional` on the other hand customises its `description`, and prints as `Optional(2)` instead (this is behaviour you'll get with IUOs in Swift 4.2 once the IUO type has been fully banished from the type system, but it's not quite yet the case in 4.1). – Hamish May 10 '18 at 21:59
  • @Hamish Interesting! Could you cook that up in an answer? Let me give you internet points – Alexander May 10 '18 at 22:15
  • Over at https://stackoverflow.com/a/49708550/2976878 :) – Hamish May 10 '18 at 22:15
0

The Optional type is an enumeration with two cases. Optional.none is equivalent to the nil literal. Optional.some(Wrapped) stores a wrapped value. Reference.

Other information about optionals that might be useful (search for Implicitly Unwrapped Optionals)

Anderson
  • 98
  • 2
  • 6