V
V
Vanya Popov2019-05-16 11:47:09
Swift
Vanya Popov, 2019-05-16 11:47:09

Problem when creating a dictionary with an optional value, why is that?

Hello!
I recently started learning Swift and the following question arose.
Let's say I created a dictionary alias:

typealias Dict = [String:(alpha:Character,num:Int)?]

Here the key is a string type, and the value is an optional of a tuple, which in turn consists of an element of character type and an integer.
Then if I want to create a dictionary with an arbitrary value, I will write: But then the compiler will give an error and require to remove the "?": Can someone explain why this is so? Shouldn't we indicate that we have a value not just a tuple, but an optional tuple ? Thanks in advance!
var dicOne: Dict = ["Key" : ( "V", 1)?]
var dicOne: Dict = ["Key" : ( "V", 1)]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
one pavel, 2019-05-16
@ryccak

Are you confusing the concepts Type and Object of this type
typealias Dict = [String:(alpha:Character,num:Int)?]
(alpha:Character,num:Int)? - here you declare a type, an optional tuple,
and in this line
var dicOne: Dict = ["Key" : ( "V", 1)?]
( "V", 1) is an object with data that will be wrapped in an optional
, the same only on a simpler example
var str:String? = "hello world"
you should open the documentation and see what the optional is
https://medium.com/ios-os-x-development/swift-opti...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question