Reputation: 4803
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
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
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