URL and string interpolation

The URL initializer (string: "") seems to refuse to initialize correctly when using string interpolation. The problem is that when I use something like

let url = URL(string: "http://192.168.1.1")

it works but next

let host = "192.168.1.1"
let url = URL(string: "http://\(host)")

no and url = nil.

Playground works, but not in code. I double-checked that the host of the variable was set correctly.

Any idea?

+4
source share
2 answers

There was a similar problem.

This worked in Swift 2, but was included in Swift 3 (I am bouncing off two of our apps similar to Facebook and Facebook Messenger):

var userId: Int!
var userType: String!

// userId and userType are set by some code somewhere else...

if let url = URL(string: "anotherappicreated://?userId=\(userId)&userType=\(userType)") {
    UIApplication.shared.openURL(url)   // Open our other app
}

Swift 2 (, !) . Swift 3 :

var userId: Int!
var userType: String!

// userId and userType are set by some code somewhere else...

if let userId = userId,        // <-- HAD TO ADD THIS
    let userType = userType,   // <-- AND THIS
    let url = URL(string: "anotherappicreated://?userId=\(userId)&userType=\(userType)") {
    UIApplication.shared.openURL(url)   // Open our other app
}
+6

, , , URL- - . , , , var.

0

Source: https://habr.com/ru/post/1654792/


All Articles