Golak Sarangi
Golak Sarangi

Reputation: 905

How to defer string interpolation in swift?

I have got a utility method that creates Url from a config. The config holds the urls with placeholders that needs to be replaced in runtime. Since string format doesn't work properly for %s, I was thinking of deferred interpolation where I should be able to construct the string only when the object is available.

For example if I have a string:

var str = http://localhost/entitylist/\(obj.key2)/entity/\(obj.key1)

I want to do something like method1(str, obj) which should give me the interpolated value .

No doubt I can achieve it with str.stringByReplacingOccurrencesOfString, still I wanted to know if there is any better way of doing it

Upvotes: 0

Views: 451

Answers (3)

latkin
latkin

Reputation: 11

Deferring interpolation can be done by using a closure. You need to create the placeholder storage before you create the closure, but you can assign the values later.

struct Obj {
    var key1: String
    var key2: String
}

var obj = Obj(key1: "", key2: "")  // create the placeholder

let str = { "http://localhost/entitylist/\(obj.key2)/entity/\(obj.key1)" }

// assign values

obj.key1 = "bar"
obj.key2 = "foo"

print(str())  // http://localhost/entitylist/foo/entity/bar

Upvotes: 1

matt
matt

Reputation: 535411

Do not misuse a format string as you are doing. There are NSString and NSURL and related methods for forming a URL properly:

let url = NSURLComponents()
url.scheme = "http"
url.host = "localhost"
var path : NSString = "/"
path = path.stringByAppendingPathComponent("entitylist")
path = path.stringByAppendingPathComponent("foo")
path = path.stringByAppendingPathComponent("entity")
path = path.stringByAppendingPathComponent("bar")
url.path = path as String
url.URL // http://localhost/entitylist/foo/entity/bar

Upvotes: 1

Golak Sarangi
Golak Sarangi

Reputation: 905

As mentioned in the comment by Martin R, using %@ is the right way of doing it

var str = "http://localhost/entitylist/%@/entity/%@"

String(format: str, arguments: ["foo", "bar"])

Upvotes: 1

Related Questions