栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Swift中编写init方法?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Swift中编写init方法?

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

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/616393.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号