Implicitly Unwrapped Optionals and println

I am learning Swift and I have doubts about implicitly deferred options.

I have a function that returns String optionally:

func findApt(aptNumber :String) -> String? { let aptNumbers = ["101", "202", "303", "404"] for element in aptNumbers { if (element == aptNumber) { return aptNumber } } // END OF for LOOP return nil } 

and an if statement for safe deployment, which uses implicitly Unwrapped Optional as a constant:

 if let apt :String! = findApt("404") { apt println(apt) println("Apartment found: \(apt)") } 

On the first line, apt unfolds on its own (β€œ404” is displayed on the result panel), but apt does not expand on the other two lines: the result panels and consoles show that the printed values ​​are optional (β€œ404”) and Apartment found: Optional (" 404 "), and in order for 404 to appear on the console, I have to use! a symbol, which, if I understand correctly, is necessary only for the manual expansion of the usual options.

Why is this happening?

My guess is that when passing println (), apt is implicitly converted from Implicitly Unwrapped Optional to regular Optional, which leads to the appearance of optional ("404") text. I like some expert advice on this, as I just start with this language.

+1
swift swift-playground optional
Aug 22 '15 at 15:14
source share
1 answer

let apt :String! = findApt("404") let apt :String! = findApt("404") does not expand optional, since you explicitly use the optional type, which is String!

If you want to deploy additional use:

 if let apt: String = findApt("404") { ... } 

or better, using type inference:

 if let apt = findApt("404") { ... } 

In the first line, apt unfolds on its own (the results pane shows "404"), but apt does not expand on the other two lines: both the result pane and the console show that the printed values ​​are Advanced ("404") and the apartment is found: Optional ("404 "), and in order for 404 to appear on the console, I have to use! a symbol that, if I understand correctly, you only need to manually expand Optionals.

Why is this happening?

This is how the console / playground is displayed. In your sample code, apt is still Optional .

You can check the type at runtime using dynamicType , i.e. println(apt.dynamicType)

+2
Aug 22 '15 at 15:25
source share



All Articles