Wiingaard
Wiingaard

Reputation: 4302

Swift 3; Appending optional string with non-optional string

I just updated to Xcode 8.0 beta 2 and swift 3.0, and I'm getting an error in some of my existing swift 2.3-code, regarding optional strings:

Binary operator '+' cannot be applied to operands of type 'String' and 'String!'

The variable "store" is an instance of a "Store"-object with properties addressStreet and addressCity, both defined as var addressStreet: String!

I'm getting the error on the addressLabel.text = ... line

if store != nil {
    addressLabel.text = store!.addressStreet + String(", ") + store!.addressCity
}

I don't get it! to me, it seems that none of the strings are optional, why am i getting this error, and how can i fix it?

Upvotes: 1

Views: 1610

Answers (1)

Arsen
Arsen

Reputation: 10951

I don't know why it's crash but code below more safe and doesn't have 'String' + 'String!' problem. Try it:

if let store = store, street = store.addressStreet, city = store.addressCity {
    addressLabel.text = "\(street), \(city)"
}

Upvotes: 1

Related Questions