Peter71
Peter71

Reputation: 2300

Swift: Conditional casts not needed but "must"?

I get a warning for "as? AnyObject" that "conditional casts always succeeds". So "?" it is not needed!? If I remove the "?", I get an error, that I must have "optional" :

func toDictionary() -> [String: AnyObject] {
    var retval = [String: AnyObject]()
    if let
        steeringItems   = self.steeringItems   as? AnyObject,
        destinationPath = self.destinationPath as? AnyObject
    {
        retval["steeringItems"] = steeringItems
        retval["gDstPath"] = destinationPath
    }
    return retval
}

What is the correct way?

Upvotes: 1

Views: 237

Answers (1)

Hamish
Hamish

Reputation: 80821

Optional binding is used to in order to unwrap optionals, and your steeringItems and destinationPath are non-optionals.

Also, because destinationPath is a String, which can be freely bridged to NSString and steeringItems is a [SteeringItem], which can be bridged to NSArray (as SteeringItem is an NSObject) – you can freely up-cast them to AnyObject. Therefore you don't need to do any conditional casting (as it would never fail).

So just don't use optional binding! Just assign the properties directly:

func toDictionary() -> [String:AnyObject] {

    var retval = [String: AnyObject]()

    retval["steeringItems"] = steeringItems
    retval["gDstPath"] = destinationPath

    return retval
}

Or more concisely:

func toDictionary() -> [String:AnyObject] {
    return ["steeringItems":steeringItems, "gDstPath":destinationPath]
}

Upvotes: 1

Related Questions