gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 05:05:09 24 4
gpt4 key购买 nike

我想用 Swift 编写一个 init 方法。这里我在 Objective-C 中初始化了一个 NSObject 类:

-(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 中编写此方法?

最佳答案

我想这可能是您类(class)的良好基础:

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()])

}

注意:这只是您如何做到这一点的原始想法,根本没有必要使用便利初始化器,但它看起来很明显,因为我对您的 final类一无所知 – 您只分享了一个方法。

关于objective-c - 如何在 Swift 中编写 init 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24302288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com