2015-10-19 88 views
1

我是Swift的新手,我想知道如何在Swift中創建參數化的字符串或宏?在swift中創建參數化的字符串或宏?

就像我們做的Objective-C:

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

如何在斯威夫特制定上述聲明?

+1

是好還是壞雨燕[少了點有](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/Migration.html)預處理器宏。[更多](http://stackoverflow.com/a/24114340/294884) – Fattie

回答

3

您可以定義全局函數:

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

也不要忘記URL編碼name

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

您也可以使用相同的代碼在橋頭

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

相同

#define kNSUserDefaultUserInfo "UserInfo" 

我想在我的項目大橋 - 頭你的代碼,並從所有文件的訪問無論是斯威夫特還是目的C.

希望這將幫助你

+0

我試過這個,但它不適合我。將它添加到網橋頭文件後,如何使用? – VRAwesome