I'm learning Swift and I have a doubt regarding Implicitly Unwrapped Optionals.
I have a function returning a String optional:
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 to perform safe unwrapping, which uses an Implicitly Unwrapped Optional as its constant:
if let apt :String! = findApt("404")
{
apt
println(apt)
println("Apartment found: \(apt)")
}
In the first line apt unwraps itself as it should (the results pane shows "404"), but in the other two lines apt does not unwrap: both the results pane and the console show that the printed values are Optional("404") and Apartment found: Optional("404"), and in order for 404 to appear on console I have to use the ! symbol, which, if I understand correctly, is only needed to manually unwrap regular Optionals.
Why does it happen?
My guess is that, when passed to println(), apt is implicitly converted from Implicitly Unwrapped Optional to regular Optional, which causes the Optional("404") text to appear, but I'd like some expert advice on the matter, as I'm just a beginner with the language.