小编典典

如何在Swift中编写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中编写此方法?


阅读 325

收藏
2020-07-07

共1个答案

小编典典

我想这可能是您上课的良好基础

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
    }

}

高级模式

我想避免将键复制粘贴到项目中,因此我将可能的键放入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()])

}

注意:那只是如何做的一个原始想法,根本不需要使用便捷的初始化程序,但是对于我对您的最终课程一无所知,这看起来是显而易见的选择–您仅共享一种方法。

2020-07-07