Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL and string interpolation

Tags:

swift

swift3

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?

like image 671
coderman Avatar asked Sep 16 '16 10:09

coderman


People also ask

What is meant by string interpolation?

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.

How do you use interpolation in string?

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.

Why is string interpolation used?

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.

Can you do string interpolation in JavaScript?

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.


1 Answers

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
}
like image 92
TenaciousJay Avatar answered Oct 12 '22 20:10

TenaciousJay