Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a dictionary value in Swift

I'm trying to get my dictionary in Swift to print out. If my dictionary is

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

and I print it out by saying

airports["ALB"]

It returns

{Some "Albany International"}

I've noticed that this also happens whenever I have an optional variable.

Is there some way to keep it from including that some?

like image 724
AndyReifman Avatar asked Oct 20 '25 09:10

AndyReifman


1 Answers

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

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 that the key is there, and you would like to avoid an error, you can do this:

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

Function print will be called only when "ALB" key is present in the dictionary, in which case alb would be assigned a non-optional String.

like image 58
Sergey Kalinichenko Avatar answered Oct 22 '25 03:10

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!