2016-05-08 2 views
1

Я пытаюсь преобразовать код цели c в быстрый. Я конвертирую многие из них, но у меня проблема с частью кода init.Super init in Swift

Как исправить мою ошибку 3. Легко исправить их удаление, если утверждение. Но для этой проблемы я не мог найти реального решения. Удаление if statement Это может вызвать проблему?

Мои коды:

My objective c code: 

-(id)init 
{ 
    self = [super init]; 
    if (self) // In swift I can delete this statement to solve my problem. Is it causing the problem? 
    { 
     [self commonInit]; 
    } 
    return self; 
} 
-(id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier 
{ 
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; 
    if (self) //Also I can delete this if to solve the error but I am not sure is it the best way 
    { 
     [self commonInit]; 
    } 
    return self; 
} 


-(void)commonInit 
{ 
    self.backgroundColor = [UIColor clearColor]; 
    self.contentView.backgroundColor = [UIColor clearColor]; 
    self.selectionStyle = UITableViewCellSelectionStyleNone; 
    self.accessoryType = UITableViewCellAccessoryNone; 

    _textView = [[UITextView alloc] init]; 

    _timeLabel = [[UILabel alloc] init]; 
    _statusIcon = [[UIImageView alloc] init]; 

    [self.contentView addSubview:_timeLabel]; 
    [self.contentView addSubview:_statusIcon]; 

} 

И мой скор код:

init() { 

     super.init() //Gives Error: Must call a designated initializer of the superclass 'UITableViewCell' 

     if self != nil { //Value of type 'MessageCell' can never be nil, comparison isn't allowed 

      self.commonInit() 
     } 
    } 

    //Added this init because Xcode gives error if not add 
    required init?(coder aDecoder: NSCoder) { 

     super.init(coder: aDecoder) 

     fatalError("init(coder:) has not been implemented") 
    } 


    override init(style: UITableViewCellStyle, reuseIdentifier: String?){ 

     super.init(style: style, reuseIdentifier: reuseIdentifier) 

     if self != nil { //Error: Value of type 'MessageCell' can never be nil, comparison isn't allowed 

      self.commonInit() 
     } 

    } 

func commonInit() { 

     //set values 

     self.backgroundColor = UIColor.clearColor() 
     self.contentView.backgroundColor = UIColor.clearColor() 
     self.selectionStyle = .None 
     self.accessoryType = .None 

     self.timeLabel = UILabel() 
     self.statusIcon = UIImageView() 

     self.contentView.addSubview(timeLabel) 
     self.contentView.addSubview(statusIcon)   
    } 
+0

Какова ваша интерпретация сообщений? – Wain

+0

@Wain Добавлены ошибки внутри кода. он говорит, что должен вызвать назначенный инициализатор суперкласса «UITableViewCell» в части init. И другая ошибка ниже этой ошибки – Arda

+0

Я видел это, я спрашиваю, что вы думаете, что они означают – Wain

ответ

2

Если вы идете внутри источников UITableViewCell, вы увидите:

public init(style: UITableViewCellStyle, reuseIdentifier: String?) 
public init?(coder aDecoder: NSCoder) 

Там нет init() , поэтому вы получаете Должен вызывать назначенный инициализатор ошибка; вы пытаетесь вызвать метод инициализации NSObject.
На первом проходе, вы могли бы написать что-то вроде этого:

init() { 
    super.init(style: UITableViewCellStyle.Default, reuseIdentifier: "example reuse id") 
    self.commonInit() 
} 
override init(style: UITableViewCellStyle, reuseIdentifier: String?){ 
    super.init(style: style, reuseIdentifier: reuseIdentifier) 
    self.commonInit() 
} 

Заметьте, что нет необходимости проверять, если сам является ноль во втором инициализаторе, как это не failable - это означает, что вы всегда будете иметь действительный и полностью инициализированный объект.
Но, видя, что теперь совсем немного дублирования, если вы все еще хотите по умолчанию init() вы можете избавиться от commonInit все вместе:

convenience init() { 
    self.init(style: UITableViewCellStyle.Default, reuseIdentifier: "example reuse id") 
} 
override init(style: UITableViewCellStyle, reuseIdentifier: String?){ 
    super.init(style: style, reuseIdentifier: reuseIdentifier) 
    //you can initialize your object here, or call your commonInit 
} 

виду, что если вам не нужны значения по умолчанию, вы также можете избавиться от первых convenience init() :)

+0

Спасибо за помощь Smnd :) Это сработало! – Arda

+0

Awesome..cheers! :) – Smnd