objective-c 如何在 Swift 中编写 init 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24302288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:21:11  来源:igfitidea点击:

How to write init method in Swift?

objective-cswiftinit

提问by Vineesh TP

I want to write an initmethod in Swift. Here I initialize an NSObjectclass in Objective-C:

我想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;
}

How can I write this method in Swift ?

如何在 Swift 中编写此方法?

回答by holex

that could be good bases for your class, I guess:

我想这可能是您班级的良好基础:

class MyClass {

    // you may need to set the proper types in accordance with your dictionarty's 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
    }

}

advanced-mode

高级模式

I would like to avoid to copy-pand-paste the keys in a project, so I'd put the possible keys into e.g. an enumlike this:

我想避免在项目中复制粘贴键,所以我将可能的键放入例如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 ""
        }
    }
}

and you can improve your convenience init(...)method like e.g. this, and in the future you can avoid any possible mistyping of the keys in your code:

并且您可以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()])

}

NOTE: that is just a raw idea of how you could do it, it is not necessary to use conveniece initializer at all, but it looked obvious choice regarding I don't know anything about your final class – you have shared one method only.

注意:这只是一个关于如何做到这一点的原始想法,根本没有必要使用方便的初始化程序,但它看起来很明显,因为我对你的最终课程一无所知——你只共享了一个方法。

回答by Shai

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

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

See Swift: Initialization

请参阅Swift:初始化

回答by abdul sathar

Do not need for call this method from other class it will get called automatically

不需要从其他类调用此方法它会自动调用

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

回答by CW0007007

try:

尝试:

initWithDictionary(dictionary : NSDictionary) {
   init()
   self.title = "... etc"
}

Source:

来源:

https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

https://docs.swift.org/swift-book/LanguageGuide/Initialization.html