|
Hello, I am trying to understand logic behind unwrapping optionals... I know, I have to unwrap dictionary key/value pair because swift always return an optional value why does not the same apply to arrays? what is the reason behind this logic?
thanks |
|
Because you declared your array with non-optional Strings. On the other hand, the key you ask for in the dictionary couldn't exist. Declare your Array with
|
|
@Hatsushira yeah, I understand this, but... My question is more like what thinking is behind this architecture of swift... Why is dicitonary always optional but array only if i declare it? Like those two feels kinda same in some ways (both conform to Collection protocol), yet array items are not optional by default. |
|
A dictionary is an array of For return type consistency (think of it as a return value from a function) the type returned from a dictionary has to be an optional. Whether it is a real value or nil, the return has to handle both. In the case of arrays, you define whether the elements are optional or not. You will either allow a Try this in Playground. Note: for the print statements you will see warnings that
You will see that the first print with the key "One" will print out The third print statement uses a key that does not exist in The final print statement shows the whole of |
|
I think that at least a portion of the answer you're looking for is that Swift does nothing to protect you from attempting to access an array element using a subscript that is out of bounds, i.e., less than zero or greater than the count of array elements minus one. If you do that, your app will crash. The result of accessing an array element is non-optional because the only alternative is a crash, not a nil result. On the other hand, it's considered normal that you may not know whether a dict contains an element having a certain key, and that you want to test whether it does. Therefore, rather than crashing the program, accessing the value for a non-existent key returns nil, which tells you that such element does not exist. |
SPONSORED Alex is the iOS & Mac developer’s ultimate AI assistant. It integrates with Xcode, offering a best-in-class Swift coding agent. Generate modern SwiftUI from images. Fast-apply suggestions from Claude 3.5 Sonnet, o3-mini, and DeepSeek R1. Autofix Swift 6 errors and warnings. And so much more. Start your 7-day free trial today!
Sponsor Hacking with Swift and reach the world's largest Swift community!
This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.
All interactions here are governed by our code of conduct.
Link copied to your pasteboard.