问题描述
我正在尝试从NSMutableURLRequest的子类中的自定义init返回一个实例:
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
}
}
但是编译器不允许这样做,并且出现错误无法分配给值:'self'是不可变的".解决此问题的正确方法是什么,为什么编译器会在此处返回错误.
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.
推荐答案
这是因为您的函数只是函数,而不是初始化程序.
This is because your function is merely a function, not an initializer.
请考虑以下示例:
class Request: NSMutableURLRequest {
convenience init (endPoint:String, methodType:RequestType, body:RequestBody,headers: [String:String]?) {
self.init(url: URL(string: endPoint)!)
}
}
在这里,我们声明便捷初始化器,该初始化器通过调用指定的初始化器来返回一个新对象.您无需分配任何内容,因为init是在对象的构造(创建)时调用的.
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.
这篇关于无法分配价值:“自我"是不可变的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!