Printing a dictionary value in Swift

I am trying to output my dictionary in Swift for printing. If my dictionary

var airports = ["ALB":"Albany International", "ORD": "O'Hare"]

      

and I will print it out saying

airports["ALB"]

      

It returns

{Some "Albany International"}

      

I noticed that this also happens when I have an optional variable.

Is there a way to keep it from turning on some?

+3


source to share


3 answers


If you know the key is there, you can print the value with an exclamation mark:

var airports = ["ALB":"Albany International", "ORD": "O'Hare"]
println(airports["ALB"])  // Prints Optional("Albany International")
println(airports["ALB"]!) // Prints Albany International

      

If you are not sure if the key is there and you want to avoid the error, you can do this:



if let alb = airports["ALB"] {
    print(alb)
}

      

The function print

will only be called when a key is present in the dictionary "ALB"

, in which case the alb

optional will be assigned String

.

+5


source


var temp_array: Dictionary = [
    1:"John",
    2:"Ann",
    3:"Tom",
    4:"Juan",
    5:"Sarah"
]
let value = temp_array[3]!;
print(value) 

      



0


source


thanks - it's all in detail and I missed the exclamation mark option.

0


source







All Articles