Cannot assign to value: 'self' is immutable

无人久伴 提交于 2020-01-24 10:30:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!