问题
I am trying to return an instance from custom init in subclass of 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
    }
}
But compiler does not allow to do the same and i get the error "Cannot assign to value: 'self' is immutable". What is the correct way to go about this and why does the compiler return an error here.
回答1:
This is because your function is merely a function, not an initializer.
Consider the following example:
class Request: NSMutableURLRequest {
    convenience init (endPoint:String, methodType:RequestType, body:RequestBody,headers: [String:String]?) {
        self.init(url: URL(string: endPoint)!)
    }
}
Here we declare convenience initializer which returns a new object by calling designated initializer. You don't have to assign anything because the init is called upon construction (creation) of the object.
来源:https://stackoverflow.com/questions/46600080/cannot-assign-to-value-self-is-immutable