I have a dictionary and I want to use some of its values as a key for another dictionary:
let key: String = String(dictionary[\"anotherKey\"])
A Swift dictionary always return an Optional.
dictionary["anotherKey"]
gives Optional(42)
, so String(dictionary["anotherKey"])
gives "Optional(42)"
exactly as expected (because the Optional type conforms to StringLiteralConvertible, so you get a String representation of the Optional).
You have to unwrap, with if let
for example.
if let key = dictionary["anotherKey"] {
// use `key` here
}
This is when the compiler already knows the type of the dictionary value.
If not, for example if the type is AnyObject, you can use as? String
:
if let key = dictionary["anotherKey"] as? String {
// use `key` here
}
or as an Int if the AnyObject is actually an Int:
if let key = dictionary["anotherKey"] as? Int {
// use `key` here
}
or use Int()
to convert the string number into an integer:
if let stringKey = dictionary["anotherKey"], intKey = Int(stringKey) {
// use `intKey` here
}
This is by design - it is how Swift's Dictionary
is implemented:
Swift’s
Dictionary
type implements its key-value subscripting as a subscript that takes and returns an optional type. [...] TheDictionary
type uses an optional subscript type to model the fact that not every key will have a value, and to give a way to delete a value for a key by assigning a nil value for that key. (link to documentation)
You can unwrap the result in an if let
construct to get rid of optional, like this:
if let val = dictionary["anotherKey"] {
... // Here, val is not optional
}
If you are certain that the value is there, for example, because you put it into the dictionary a few steps before, you could force unwrapping with the !
operator as well:
let key: String = String(dictionary["anotherKey"]!)
You are misunderstanding the result. The String
initializer does not return an optional. It returns the string representation of an optional. It is an non-optional String with value "Optional(42)"
.
You can also avoid force unwrapping by using default for the case that there is no such key in dictionary
var dictionary = ["anotherkey" : 42]
let key: String =
String(dictionary["anotherkey", default: 0])
print(key)