VRAwesome
VRAwesome

Reputation: 4803

Create parameterised string or macro in swift?

I am new to Swift and I want to know that how can I create parameterised strings or macros in Swift ?

Like we do in Objective-C :

#define SEARCH(name, limits) [[NSString stringWithFormat:@"https://someURL.com/search?term=%@&limit=%ld", name, limits]

How can formulate above statement in Swift ?

Upvotes: 1

Views: 675

Answers (2)

Arvind Kumar
Arvind Kumar

Reputation: 2411

You can also use same code in Bridge-Header

#define SEARCH(name, limits) [[NSString stringWithFormat:@"https://someURL.com/search?term=%@&limit=%ld", name, limits]

same as

#define kNSUserDefaultUserInfo "UserInfo"

I tried your code in my Project Bridge-Header and its accessible from all files whether it is Swift or Objective C.

Hope this will help you

Upvotes: 0

mixel
mixel

Reputation: 25846

You can define global function:

func search(name: String, _ limits: Int) -> String {
    return "https://someURL.com/search?term=\(name)&limit=\(limits)"
}

Also do not forget to URL-encode name:

func search(name: String, _ limits: Int) -> String {
    let urlEncodedName = name.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) ?? ""
    return "https://someURL.com/search?term=\(urlEncodedName)&limit=\(limits)"
}

Upvotes: 3

Related Questions