Подтвердить что ты не робот

Как написать метод Init в Swift

Я хочу написать метод init в swift, здесь я дал NSObject класс модели в Objective-C

-(id)initWithNewsDictionary:(NSDictionary *)dictionary
{
    self = [super init];
    if (self) {
        self.title           = dictionary[@"title"];
        self.shortDescription = dictionary[@"description"];
        self.newsDescription = dictionary[@"content:encoded"];
        self.link            = dictionary[@"link"];
        self.pubDate         = [self getDate:dictionary[@"pubDate"]];

    }
    return self;
}

Как я могу написать этот метод в swift?

4b9b3361

Ответ 1

что может быть хорошей основой для вашего класса, я думаю:

class MyClass {

    // you may need to set the proper types in accordance with your dictionarty content
    var title: String?
    var shortDescription: String?
    var newsDescription: String?
    var link: NSURL?
    var pubDate: NSDate?

    //

    init () {
        // uncomment this line if your class has been inherited from any other class
        //super.init()
    }

    //

    convenience init(_ dictionary: Dictionary<String, AnyObject>) {
        self.init()

        title = dictionary["title"] as? NSString
        shortDescription = dictionary["shortDescription"] as? NSString
        newsDescription = dictionary["newsDescription"] as? NSString
        link = dictionary["link"] as? NSURL
        pubDate = self.getDate(dictionary["pubDate"])

    }

    //

    func getDate(object: AnyObject?) -> NSDate? {
        // parse the object as a date here and replace the next line for your wish...
        return object as? NSDate
    }

}

расширенный режим

Я бы хотел избежать копирования-вставки ключей в проекте, поэтому я бы поместил возможные ключи, например. a enum следующим образом:

enum MyKeys : Int {
    case KeyTitle, KeyShortDescription, KeyNewsDescription, KeyLink, KeyPubDate
    func toKey() -> String! {
        switch self {
        case .KeyLink:
            return "title"
        case .KeyNewsDescription:
            return "newsDescription"
        case .KeyPubDate:
            return "pubDate"
        case .KeyShortDescription:
            return "shortDescription"
        case .KeyTitle:
            return "title"
        default:
            return ""
        }
    }
}

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

convenience init(_ dictionary: Dictionary<String, AnyObject>) {
    self.init()

    title = dictionary[MyKeys.KeyTitle.toKey()] as? NSString
    shortDescription = dictionary[MyKeys.KeyShortDescription.toKey()] as? NSString
    newsDescription = dictionary[MyKeys.KeyNewsDescription.toKey()] as? NSString
    link = dictionary[MyKeys.KeyLink.toKey()] as? NSURL
    pubDate = self.getDate(dictionary[MyKeys.KeyPubDate.toKey()])

}

ПРИМЕЧАНИЕ: это всего лишь исходная идея о том, как вы могли это сделать, нет необходимости использовать инициализатор условных знаков вообще, но он выглядел очевидным выбором в отношении того, что я ничего не знаю о вашем последнем классе - вы поделились одним только метод.

Ответ 2

class myClass {
    var text: String
    var response: String?

    init(text: String) {
        self.text = text
    }
}

См. Swift: Инициализация (лучше в будущем в будущем).

Ответ 3

Не нужно для вызова этого метода из другого класса, он будет автоматически вызван

override init()
    {
        super.init()
         //synthesize.delegate = self
       // println("my array elements are \(readingData)")

    }

Ответ 4

попробовать:

initWithDictionary(dictionary : NSDictionary) {

   init()

   self.title = ... etc

}

Источник: