我是Swift的新手,我想知道如何在Swift中创建参数化字符串或宏?
就像我们在Objective-C中所做的那样:
#define SEARCH(name, limits) [[NSString stringWithFormat:@"https://someURL.com/search?term=%@&limit=%ld", name, limits]
如何在Swift中制定上述语句?
答案 0 :(得分:3)
您可以定义全局功能:
func search(name: String, _ limits: Int) -> String {
return "https://someURL.com/search?term=\(name)&limit=\(limits)"
}
另请不要忘记对name
进行网址编码:
func search(name: String, _ limits: Int) -> String {
let urlEncodedName = name.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) ?? ""
return "https://someURL.com/search?term=\(urlEncodedName)&limit=\(limits)"
}
答案 1 :(得分:0)
您也可以在Bridge-Header中使用相同的代码
#define SEARCH(name, limits) [[NSString stringWithFormat:@"https://someURL.com/search?term=%@&limit=%ld", name, limits]
与
相同#define kNSUserDefaultUserInfo "UserInfo"
我在Project Bridge-Header中尝试了您的代码,无论是Swift还是Objective C,都可以访问所有文件。
希望这会对你有所帮助