ios - swift新手请教,我在swift中调用self.init,报错了,怎么回事?
伊谢尔伦
伊谢尔伦 2017-04-18 09:47:55
0
2
468

在方法中药调用 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
    
}

}

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
小葫芦

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
  }
左手右手慢动作

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!