It seems URL initializer (string: "") refuses to initialize properly when using string interpolation. The problem is, when I use something like
let url = URL(string: "http://192.168.1.1")
it works, but the following
let host = "192.168.1.1"
let url = URL(string: "http://\(host)")
does not and url = nil.
In Playground both work but not in the code. I did double check if the variable host is properly set.
Any idea?
In computer programming, string interpolation (or variable interpolation, variable substitution, or variable expansion) is the process of evaluating a string literal containing one or more placeholders, yielding a result in which the placeholders are replaced with their corresponding values.
An interpolated string is a string literal that might contain interpolation expressions. When an interpolated string is resolved to a result string, items with interpolation expressions are replaced by the string representations of the expression results.
String Interpolation is a process in which the placeholder characters are replaced with the variables (or strings in this case) which allow to dynamically or efficiently print out text output. String Interpolation makes the code more compact and avoids repetition of using variables to print the output.
String interpolation in JavaScript is a process in which an expression is inserted or placed in the string. To insert or embed this expression into the string a template literal is used. By using string interpolation in JavaScript, values like variables and mathematical expressions and calculations can also be added.
Had a similar problem.
This worked in Swift 2 but broke in Swift 3 (I bounce between 2 of our apps, similar to Facebook & 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
}
In Swift 2 implicitly unwrapped optionals (variables declared with the !) worked without having to unwrap them. In Swift 3 it seems you must explicitly unwrap optionals:
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With