0
let allPlaces = resultsArray.map({ (param) -> Places in
                        return Places(dictionary: param )
                    })
                    print("All Places \(allPlaces[0].placeName)")

The output of the above code is:

All Places Optional("Subway")

In the below code the var is not optional. But the print statement prints it as Optional. Should it not print All Places "Subway"?

class Places: NSObject {


    var name:String!


    init(dictionary:Dictionary<String, Any>) {

        name = dictionary["name"] as? String
    }
}
NNikN
  • 3,720
  • 6
  • 44
  • 86
  • From this place dictionary["name"] as? String it's giving optional. Changing it to dictionary["name"] as! String will give you non-optional – Sivajee Battina Apr 05 '17 at 05:12
  • Try this `print("All Places " + allPlaces[0].placeName)` – Danh Huynh Apr 05 '17 at 05:18
  • `dictionary["name"] as? String` makes it optional value. – byJeevan Apr 05 '17 at 05:33
  • See [Swift 3 incorrect string interpolation with implicitly unwrapped Optionals](http://stackoverflow.com/q/39537177/2976878) – an IUO is treated as a strong optional wherever it can be type-checked as one. – Hamish Apr 05 '17 at 08:54
  • Whenever you put `!` or `?` in front of a "type", it is actually an `Optional` type. The only difference is that you are telling the compiler that when you read the `name` property you don't want to handle its nullability ('cause you are sure it won't ever be `nil`), but it still could be `nil`. Said this, you can simply define the property as `var name:String`. – eMdOS Mar 31 '20 at 17:21

2 Answers2

0
var name:String!

You have declared name as implicitly unwrapped optional. From Swift 3 onwards it will only be force unwrapped if they need to be type checked locally. Otherwise it will be treated as normal optional only.

 print("All Places \(allPlaces[0].name)")

Here there is no type checking involved, so name would be still Optional.

If you do like

let name:String = allPlaces[0].name
print("All Places \(name)")   

Output will be "All Places Subway"

or you need to force unwrap it

 print("All Places \(allPlaces[0].name!)")

This would cause crash if the name is nil, you should take care of it. If there is a chance name can be nil then use var name: String? so compiler force you to unwrap explicitly.

Anil Varghese
  • 42,757
  • 9
  • 93
  • 110
-1

Change 'as?' to 'as!'.

  • The exclamation point means it absolutely clear.

  • The question mark means optional binding.

[Source]

class Places: NSObject {


    var name:String!


    init(dictionary:Dictionary<String, Any>) {

        name = dictionary["name"] as! String 

    }
}

Another way

print("All Places \(allPlaces[0].placeName)")

to

print("All Places \(allPlaces[0].placeName!)")

or

print("All Places \(allPlaces[0].placeName ?? "")")