2017-10-06 56 views
0

我試圖在NSMutableURLRequest的子類返回從自定義初始化一個實例:無法指定值:「自我」是不可改變的

class Request: NSMutableURLRequest { 

    func initWith(endPoint:String, methodType:RequestType, body:RequestBody,headers: [String:String]?) { 
     self = NSMutableURLRequest.init(url: URL.init(string: endPoint, relativeTo: URL?)) 
     //return request 

    } 
} 

但是編譯器不允許這樣做,我得到的錯誤「無法賦值:'self'是不可變的「。什麼是正確的方式去做這件事,爲什麼編譯器在這裏返回一個錯誤。

+0

不相關,但不要在Swift 3中使用'NSMutableURLRequest'。使用本地結構'URLRequest' – vadian

+0

對自定義初始化器的良好閱讀:https://stackoverflow.com/questions/26495586/best-practice-to-implement-a-failable-initializer-in-swift – Hexfire

回答

1

這是因爲你的功能只是一個功能,而不是一個初始化程序。

請看下面的例子:

class Request: NSMutableURLRequest { 

    convenience init (endPoint:String, methodType:RequestType, body:RequestBody,headers: [String:String]?) { 
     self.init(url: URL(string: endPoint)!) 
    } 

} 

這裏我們聲明方便初始化其回報通過調用指定的初始化一個新的對象。你不必分配任何東西,因爲在構造(創建)對象時會調用init。