Reputation: 5713
I have pretty simple example and have no clue why it doesn't work as expected.
var list:Array<Int> = [1,2,3,4,5]
var item:Int?
for var index = 0; index < list.count; index++ {
item! = list[index]
item = item + 5 // <-- error value of optional type 'Int?' not unwrapped
}
Why Swift forces me to write: item = item! + 5
I unwrapped it here: item! = list[index]
and if list returns nil
- the Exception will be thrown.
As I understand on this step a.e.: item! = list[index]
the item
is not nil
I tried several options like:
item! = list[index] as Int!
item! = list[index] as AnyOblect! as? Int
But still get the same demand to write item = item! + 5
I use playground
Upvotes: 0
Views: 620
Reputation: 18171
Let me break it down for you:
var item:Int?
tells the compiler that whenever the word item
is used, it refers to a variable of type optional Int
(aka Int?
).
var item:Int
on the other hand, tells the compiler that whenever the word item
is used, it refers to a variable simply of type Int
.
In order to access the unwrapped value of your variable declared in var item:Int?
, you will always have to use item!
. The compiler is not going to guess whether the variable item
has a value or not. That, after all, is the the whole purpose of optionals. To make it clear that these kind of variables may or may not have a value.
Essentially, what I'm trying to say is that a variable once declared as an optional, will always be an optional regardless of whether it contains a value or not. To get the unwrapped value, you will always have to use the character !
, unless you decide to store it's value in another variable (ex. var unwrappedItem = item!
)
To get rid of your error, simply declare your item
variable to be of type Int
, and not Int?
.
As to why Swift throws an error instead of just letting the runtime raise an exception, it's just an extra precaution to probably discourage people from using bad practice.
Upvotes: 3