8

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.

Suneel Kumar
  • 1,650
  • 2
  • 21
  • 31
Singh
  • 2,151
  • 3
  • 15
  • 30
  • Not related but do not use `NSMutableURLRequest` in Swift 3 at all. Use the native struct `URLRequest` – vadian Oct 06 '17 at 07:17
  • Good read on custom initializers: https://stackoverflow.com/questions/26495586/best-practice-to-implement-a-failable-initializer-in-swift – Hexfire Oct 06 '17 at 07:29

1 Answers1

8

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.

Hexfire
  • 5,945
  • 8
  • 32
  • 42