Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot assign to value: 'self' is immutable

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.

like image 674
Singh Avatar asked Oct 06 '17 07:10

Singh


1 Answers

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.

like image 145
Hexfire Avatar answered Oct 11 '22 03:10

Hexfire