在方法中药调用 self = self.init,报错信息是:Cannot assign to value:'self'is immutable
代码如下:
class Node:NSObject{
var parentID:Int?//父节点的id,如果为-1表示该节点为根节点
var nodeID:Int?//本节点的id
var name:NSString?//本节点的名称
var depth:Int?//本节点的深度
var expand:Bool?//该节点是否处于展开状态
//快速实例化该对象模型
func initWithParentID(parentID:Int,nodeID:Int,name:NSString,depth:Int,expand:Bool) -> Self{
self = self.init
return self
}
}
高洛峰2017-04-18 09:49:55
Isn’t the error reporting quite clear? Self cannot be modified - -
Call the initialization function of the parent class first
init(parentID: Int, nodeID: Int, name: NSString, depth: Int, expand:Bool) {
super.init()
self.parentID = parentID
self.nodeID = nodeID
self.name = name
self.depth = depth
self.expand = expand
}
ringa_lee2017-04-18 09:49:55
Basic reason:
Swift’s initialization chain is different from OC. OC uniformly inherits from NSObject, so super.init in OC is the initialization parent class.
But Swift initializes itself first, and then goes up the inheritance chain to initialize the properties inherited from the parent class. After reaching the base class, it then completes the initialization operation downwards.