Search code examples
stringswift3string-concatenationios10xcode8

Swift 3.0 String concatenation leaves "Optional"


Since Swift 3.0 I have some troubles with Strings, especially with concatenation. 1st example would be what I used since I started using Swift to define my url strings.

internal let host: String! = "https://host.io/"
let urlString = "\(host)oauth/access_token"

where host is defined as at the beginning of the class. This worked perfectly until Swift 3.0, now that prints out like this:

Optional("https://host.io/")oauth/access_token

which is very strange. Now I have to write this

let urlString = host + "oauth/access_token"

To get the expected output.

https://host.io/oauth/access_token

Another - I guess similar problem I'm having with Strings is this. I'm again concatenating strings but this time I'm using + ilke with urlString - but this time that doesn't work. Line of code looks like this:

self.labelName.text = currentUser.name + " " + String(describing: ageComponents.year)

which unfortunately produces string like this: "My Name Optional(26)". In this case I don't have a solution String(describing: ageComponents.year) is not an optional and it doesn't allow me to do things like String(describing: ageComponents.year) ?? "whatever"

Anyone seen something similar?


Solution

  • In Swift 3 all properties of the native struct DateComponents are optionals unlike the Foundation NSDateComponents counterparts.

    var year: Int? { get set }
    

    You need to unwrap it. If you specified the unit year in ageComponents you can do that safely.