我想这可能是您上课的良好基础
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()])}注意:那只是如何做的一个原始想法,根本不需要使用便捷的初始化程序,但是对于我对您的最终课程一无所知,这看起来是显而易见的选择–您仅共享一种方法。



