想要实现类似于这种效果:
class Message { var id:String var seq:Int64 var type:MessageType var directionType:MessageDirectionType var senderId:String var receiverId:String var timestamp:NSDate var senderName:String var senderAvatar:UIImage var timestampStr:String senderName = "" convenience init(message:Message){ self.init() self.id = message.id self.seq = message.seq self.type = message.type self.directionType = message.directionType self.senderId = message.senderId self.receiverId = message.receiverId self.timestamp = message.timestamp self.senderName = message.senderName self.senderAvatar = message.senderAvatar self.senderAvatarLarge = message.senderAvatarLarge self.isDisplayTimestamp = message.isDisplayTimestamp self.isDisplaySenderName = message.isDisplaySenderName self.timestampStr = message.timestampStr } } class NotificationMessage: Message { var subType:NotificationType override init() { super.init() convenience init(message:Message){ self.init() super.init(message: message) self.type = MessageType.Notification } } |
即:
某个父类
parentClass
有个继承的子类
subClass
在subClass中想要方便的实现一个:
传入一个父类的变量,然后初始化出了一个子类,
且已经得到父类变量的所有的域的值了
向上述那种直接
convenience init
中使用:
self.init
和
super.init
是会报错的:
Initializer cannot both delegate (‘self.init’) and chain to a superclass initializer (‘super.init’) |
搜:
Initializer cannot both delegate (‘self.init’) and chain to a superclass initializer (‘super.init’)
Initializer cannot both delegate and chain to a superclass initializer super.init
Swift: How to initialize instance of a class within a class – Stack Overflow
The Swift Programming Language (Swift 2.1): Initialization
然后折腾了半天,终于搞定了:
class Message { var id:String var seq:Int64 var type:MessageType var directionType:MessageDirectionType var senderId:String var receiverId:String var timestamp:NSDate var senderName:String var senderAvatar:UIImage var timestampStr:String senderName = "" func copyMessage(message:Message){ } class NotificationMessage: Message { var subType:NotificationType override init() { super.init() super.copyMessage(message) self.type = MessageType.Notification self.subType = notificationMessage.subType self.type = MessageType.Notification } let notificationMessage:NotificationMessage = NotificationMessage(message: newMessage) |
即可。
转载请注明:在路上 » [已解决]swift实现类的初始化时候传入父类变量的初始化