我有一個漂亮的標準問題在這裏,我有點困惑如何讓更快捷的傳統事物更優雅。Swift中的重構代碼
我在我的APIClient中有一個基本的URL字符串,一個用於不同方法的路徑,方法可能會傳入一個可選的字符串。
我該如何寫這個,使它更清潔?我覺得我寫SWIFT代碼,但不使用任何新的結構的(如門衛,讓)等
// call the API
ApiClient.sharedInstance.getUser("56cfffce227a6c2c9b000001", successCompletion: successCompletion, failureCompletion: failureCompletion)
// setting the current URL
let currentURL = String("http://localhost:3000")
// class definition
class ApiClient {
var baseURL:String!;
// have to init the string class for the
init (base:String){
self.baseURL = base
}
class var sharedInstance: ApiClient {
struct Static{
static let instance = ApiClient(base: currentURL)
}
return Static.instance
}
func getUser(user_id: String?, successCompletion: ResultHandler<User>, failureCompletion:ResultHandler<FailureReason>){
// this is awkward
var url: URLStringConvertible!
// this is even more awkward
if user_id != nil {
url = "\(currentURL)/users/\(user_id!).json"
} else {
url = "\(currentURL)/users/me"
}
}
}
創建單更妙的是這一個班輪:'靜態令sharedInstance = MyClass的()'HTTP:// krakendev。 io/blog/the-right-way-to-write-a-singleton –
潛在的問題是你只能設置一次,所以它不是很通用。 – PeejWeej
謝謝!這對單身人士有什麼好處? –