我想init在Swift中编写一个方法。在这里,我NSObject在Objective-C中初始化一个类:
init
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 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
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(...)
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()]) }
注意:那只是如何做的一个原始想法,根本不需要使用便捷的初始化程序,但是对于我对您的最终课程一无所知,这看起来是显而易见的选择–您仅共享一种方法。