“錯(cuò)誤”的使用 Swift 中的 Extension

作者:Natasha埋凯,原文鏈接,原文日期:2016-03-29譯者:bestswifter扫尖;校對(duì):shanks递鹉;定稿:Channe
別人一看到我的 Swift 代碼,立刻就會(huì)問我為什么如此頻繁的使用 extension藏斩。這是前幾天在我寫的另一篇文章中收到的評(píng)論:

A83A969C-496C-43C0-88DE-7D8ECDF21EFA.png

我大量使用 extension 的主要目的是為了提高代碼可讀性躏结。以下是我喜歡使用 extension 的場景,盡管 extension 并非是為這些場景設(shè)計(jì)的狰域。

私有的輔助函數(shù)

在 Objective-C 中媳拴,我們有 .h 文件和 .m 文件黄橘。同時(shí)管理這兩個(gè)文件(以及在工程中有雙倍的文件)是一件很麻煩的事情,好在我們只要快速瀏覽 .h 文件就可以知道這個(gè)類對(duì)外暴露的 API屈溉,而內(nèi)部的信息則被保存在 .m 文件中塞关。在 Swift 中,我們只有一個(gè)文件子巾。

為了一眼就看出一個(gè) Swift 類的公開方法(可以被外部訪問的方法)帆赢,我把內(nèi)部實(shí)現(xiàn)都寫在一個(gè)私有的 extension 中,比如這樣:
// 這樣可以一眼看出來线梗,這個(gè)結(jié)構(gòu)體中椰于,那些部分可以被外部調(diào)用

struct TodoItemViewModel {
    let item: TodoItem
    let indexPath: NSIndexPath

    var delegate: ImageWithTextCellDelegate {
    return TodoItemDelegate(item: item)
    }

    var attributedText: NSAttributedString {
    // the itemContent logic is in the private extension
    // keeping this code clean and easy to glance at
        return itemContent
    }
}

// 把所有內(nèi)部邏輯和外部訪問的 API 區(qū)隔開來
// MARK: 私有的屬性和方法
private extension TodoItemViewModel {

static var spaceBetweenInlineImages: NSAttributedString {
    return NSAttributedString(string: "   ")
}

var itemContent: NSAttributedString {
    let text = NSMutableAttributedString(string: item.content, attributes: [NSFontAttributeName : SmoresFont.regularFontOfSize(17.0)])
    
    if let dueDate = item.dueDate {
        appendDueDate(dueDate, toText: text)
    }
    
    for assignee in item.assignees {
        appendAvatar(ofUser: assignee, toText: text)
    }
    
    return text
}

func appendDueDate(dueDate: NSDate, toText text: NSMutableAttributedString) {
    
    if let calendarView = CalendarIconView.viewFromNib() {
        calendarView.configure(withDate: dueDate)
        
        if let calendarImage = UIImage.imageFromView(calendarView) {
            appendImage(calendarImage, toText: text)
        }
    }
}

func appendAvatar(ofUser user: User, toText text: NSMutableAttributedString) {
    if let avatarImage = user.avatar {
        appendImage(avatarImage, toText: text)
    } else {
        appendDefaultAvatar(ofUser: user, toText: text)
        downloadAvatarImage(forResource: user.avatarResource)
    }
}

func downloadAvatarImage(forResource resource: Resource?) {
    if let resource = resource {
        KingfisherManager.sharedManager.retrieveImageWithResource(resource,
                                                                  optionsInfo: nil,
                                                                  progressBlock: nil)
        { image, error, cacheType, imageURL in
            if let _ = image {
                dispatch_async(dispatch_get_main_queue()) {
                    NSNotificationCenter.defaultCenter().postNotificationName(TodoItemViewModel.viewModelViewUpdatedNotification, object: self.indexPath)
                }
            }
        }
    }
}

func appendDefaultAvatar(ofUser user: User, toText text: NSMutableAttributedString) {
    if let defaultAvatar = user.defaultAvatar {
        appendImage(defaultAvatar, toText: text)
    }
}

func appendImage(image: UIImage, toText text: NSMutableAttributedString) {
    text.appendAttributedString(TodoItemViewModel.spaceBetweenInlineImages)
    let attachment = NSTextAttachment()
    attachment.image = image
    let yOffsetForImage = -7.0 as CGFloat
    attachment.bounds = CGRectMake(0.0, yOffsetForImage, image.size.width, image.size.height)
    let imageString = NSAttributedString(attachment: attachment)
    text.appendAttributedString(imageString)
   }
}

注意,在上面這個(gè)例子中仪搔,屬性字符串的計(jì)算邏輯非常復(fù)雜瘾婿。如果把它寫在結(jié)構(gòu)體的主體部分中,我就無法一眼看出這個(gè)結(jié)構(gòu)體中哪個(gè)部分是重要的(也就是 Objective-C 中寫在 .h 文件中的代碼)烤咧。在這個(gè)例子中偏陪,使用 extension 使我的代碼結(jié)構(gòu)變得更加清晰整潔
這樣一個(gè)很長的 extension 也為日后重構(gòu)代碼打下了良好的基礎(chǔ)。我們有可能把這段邏輯抽取到一個(gè)單獨(dú)的結(jié)構(gòu)體中煮嫌,尤其是當(dāng)這個(gè)屬性字符串可能在別的地方被用到時(shí)笛谦。但在編程時(shí)把這段代碼放在私有的 extension 里面是一個(gè)良好的開始。

分組

我最初開始使用 extension 的真正原因是在 Swift 剛誕生時(shí)昌阿,無法使用 pragma 標(biāo)記(譯注:Objective-C 中的 #pragma mark)揪罕。是的,這就是我在 Swift 剛誕生時(shí)想做的第一件事宝泵。我使用 pragma 來分割 Objective-C 代碼好啰,所以當(dāng)我開始寫 Swift 代碼時(shí),我需要它儿奶。
所以我在 WWDC Swift 實(shí)驗(yàn)室時(shí)詢問蘋果工程師如何在 Swift 中使用 pragma 標(biāo)記框往。和我交流的那位工程師建議我使用 extension 來替代 pragma 標(biāo)記。于是我就開始這么做了闯捎,并且立刻愛上了使用 extension椰弊。
盡管 pragma 標(biāo)記(Swift 中的 //MARK)很好用,但我們很容易忘記給一段新的代碼加上 MARK 標(biāo)記瓤鼻,尤其是你處在一個(gè)具有不同代碼風(fēng)格的小組中時(shí)秉版。這往往會(huì)導(dǎo)致若干個(gè)無關(guān)函數(shù)被放在了同一個(gè)組中,或者某個(gè)函數(shù)處于錯(cuò)誤的位置茬祷。所以如果有一組函數(shù)應(yīng)該寫在一起清焕,我傾向于把他們放到一個(gè) extension 中。
一般我會(huì)用一個(gè) extension 存放 ViewController 或者 AppDelegate 中所有初始化 UI 的函數(shù),比如:

private extension AppDelegate {

func configureAppStyling() {
    styleNavigationBar()
    styleBarButtons()
}

func styleNavigationBar() {
    UINavigationBar.appearance().barTintColor = ColorPalette.ThemeColor
    UINavigationBar.appearance().tintColor = ColorPalette.TintColor
    
    UINavigationBar.appearance().titleTextAttributes = [
        NSFontAttributeName : SmoresFont.boldFontOfSize(19.0),
        NSForegroundColorAttributeName : UIColor.blackColor()
    ]
}

func styleBarButtons() {
    let barButtonTextAttributes = [
        NSFontAttributeName : SmoresFont.regularFontOfSize(17.0),
        NSForegroundColorAttributeName : ColorPalette.TintColor
    ]
    UIBarButtonItem.appearance().setTitleTextAttributes(barButtonTextAttributes, forState: .Normal)
}
}

或者把所有和通知相關(guān)的邏輯放到一起:

extension TodoListViewController {

// 初始化時(shí)候調(diào)用
func addNotificationObservers() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onViewModelUpdate:"), name: TodoItemViewModel.viewModelViewUpdatedNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("onTodoItemUpdate:"), name: TodoItemDelegate.todoItemUpdatedNotification, object: nil)
}

func onViewModelUpdate(notification: NSNotification) {
    if let indexPath = notification.object as? NSIndexPath {
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .None)
    }
}

func onTodoItemUpdate(notification: NSNotification) {
    if let itemObject = notification.object as? ValueWrapper<TodoItem> {
        let updatedItem = itemObject.value
        let updatedTodoList = dataSource.listFromUpdatedItem(updatedItem)
        dataSource = TodoListDataSource(todoList: updatedTodoList)
    }
}
}
遵守協(xié)議
struct TodoItemViewModel {
static let viewModelViewUpdatedNotification = "viewModelViewUpdatedNotification"

let item: TodoItem
let indexPath: NSIndexPath

var delegate: ImageWithTextCellDelegate {
    return TodoItemDelegate(item: item)
}

var attributedText: NSAttributedString {
    return itemContent
}
}

// 遵循 ImageWithTextCellDataSource 協(xié)議實(shí)現(xiàn)
extension TodoItemViewModel: ImageWithTextCellDataSource {

var imageName: String {
    return item.completed ? "checkboxChecked" : "checkbox"
}

var attributedText: NSAttributedString {
    return itemContent
}
}

這種方法同樣非常適用于分割 UITableViewDataSource 和 UITableViewDelegate 的代碼:

// MARK: 表格視圖數(shù)據(jù)源
extension TodoListViewController: UITableViewDataSource {

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return dataSource.sections.count
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return dataSource.numberOfItemsInSection(section)
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(String.fromClass(ImageWithTextTableViewCell), forIndexPath: indexPath) as! ImageWithTextTableViewCell
    let viewModel = dataSource.viewModelForCell(atIndexPath: indexPath)
    cell.configure(withDataSource: viewModel, delegate: viewModel.delegate)
    return cell
}
}
// MARK: 表格視圖代理
extension TodoListViewController: UITableViewDelegate {

// MARK: 響應(yīng)列選擇
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier(todoItemSegueIdentifier, sender: self)
}

// MARK: 頭部視圖填充
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    if dataSource.sections[section] == TodoListDataSource.Section.DoneItems {
        let view = UIView()
        view.backgroundColor = ColorPalette.SectionSeparatorColor
        return view
    }
    return nil
}

func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    if dataSource.sections[section] == TodoListDataSource.Section.DoneItems {
        return 1.0
    }
    
    return 0.0
}

// MARK: 刪除操作處理
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
    return true
}

func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [UITableViewRowAction]?  {
    
    let deleteAction = UITableViewRowAction(style: .Destructive, title: "Delete") { [weak self] action , indexPath in
        if let updatedTodoList = self?.dataSource.listFromDeletedIndexPath(indexPath) {
            self?.dataSource = TodoListDataSource(todoList: updatedTodoList)
        }
    }
    
    return [deleteAction]
}
}
模型(Model)

這是一種我在使用 Objective-C 操作 Core Data 時(shí)就喜歡采用的方法秸妥。由于模型發(fā)生變化時(shí)滚停,Xcode 會(huì)生成相應(yīng)的模型,所以函數(shù)和其他的東西都是寫在 extension 或者 category 里面的粥惧。

在 Swift 中键畴,我盡可能多的嘗試使用結(jié)構(gòu)體,但我依然喜歡使用 extension 將 Model 的屬性和基于屬性的計(jì)算分割開來突雪。這使 Model 的代碼更容易閱讀:

struct User {
let id: Int
let name: String
let avatarResource: Resource?
}

extension User {

var avatar: UIImage? {
    if let resource = avatarResource {
        if let avatarImage = ImageCache.defaultCache.retrieveImageInDiskCacheForKey(resource.cacheKey) {
            let imageSize = CGSize(width: 27, height: 27)
            let resizedImage = Toucan(image: avatarImage).resize(imageSize, fitMode: Toucan.Resize.FitMode.Scale).image
            return Toucan.Mask.maskImageWithEllipse(resizedImage)
        }
    }
    return nil
}

var defaultAvatar: UIImage? {
    if let defaultImageView = DefaultImageView.viewFromNib() {
        defaultImageView.configure(withLetters: initials)
        if let defaultImage = UIImage.imageFromView(defaultImageView) {
            return Toucan.Mask.maskImageWithEllipse(defaultImage)
        }
    }
    
    return nil
}

var initials: String {
    var initials = ""
    
    let nameComponents = name.componentsSeparatedByCharactersInSet(.whitespaceAndNewlineCharacterSet())
    
    // 得到第一個(gè)單詞的第一個(gè)字母
    if let firstName = nameComponents.first, let firstCharacter = firstName.characters.first {
        initials.append(firstCharacter)
    }
    
    // 得到最后一個(gè)單詞的第一個(gè)字母
    if nameComponents.count > 1 {
        if let lastName = nameComponents.last, let firstCharacter = lastName.characters.first {
            initials.append(firstCharacter)
        }
    }
    
    return initials
}
}

長話短說(TL;DR)

盡管這些用法可能不那么“傳統(tǒng)”起惕,但 Swift 中 extension 的簡單使用,可以讓代碼質(zhì)量更高咏删,更具可讀性惹想。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市饵婆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌戏售,老刑警劉巖侨核,帶你破解...
    沈念sama閱讀 218,941評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異灌灾,居然都是意外死亡搓译,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,397評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門锋喜,熙熙樓的掌柜王于貴愁眉苦臉地迎上來些己,“玉大人,你說我怎么就攤上這事嘿般《伪辏” “怎么了?”我有些...
    開封第一講書人閱讀 165,345評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵炉奴,是天一觀的道長逼庞。 經(jīng)常有香客問我,道長瞻赶,這世上最難降的妖魔是什么赛糟? 我笑而不...
    開封第一講書人閱讀 58,851評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮砸逊,結(jié)果婚禮上璧南,老公的妹妹穿的比我還像新娘。我一直安慰自己师逸,他們只是感情好司倚,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,868評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般对湃。 火紅的嫁衣襯著肌膚如雪崖叫。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,688評(píng)論 1 305
  • 那天拍柒,我揣著相機(jī)與錄音心傀,去河邊找鬼。 笑死拆讯,一個(gè)胖子當(dāng)著我的面吹牛脂男,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播种呐,決...
    沈念sama閱讀 40,414評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼宰翅,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了爽室?” 一聲冷哼從身側(cè)響起汁讼,我...
    開封第一講書人閱讀 39,319評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎阔墩,沒想到半個(gè)月后嘿架,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,775評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡啸箫,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年耸彪,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片忘苛。...
    茶點(diǎn)故事閱讀 40,096評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蝉娜,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出扎唾,到底是詐尸還是另有隱情召川,我是刑警寧澤,帶...
    沈念sama閱讀 35,789評(píng)論 5 346
  • 正文 年R本政府宣布胸遇,位于F島的核電站扮宠,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏狐榔。R本人自食惡果不足惜坛增,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,437評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望薄腻。 院中可真熱鬧收捣,春花似錦、人聲如沸庵楷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,993評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至咐蚯,卻和暖如春童漩,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背春锋。 一陣腳步聲響...
    開封第一講書人閱讀 33,107評(píng)論 1 271
  • 我被黑心中介騙來泰國打工矫膨, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人期奔。 一個(gè)月前我還...
    沈念sama閱讀 48,308評(píng)論 3 372
  • 正文 我出身青樓侧馅,卻偏偏與公主長得像,于是被迫代替她去往敵國和親呐萌。 傳聞我的和親對(duì)象是個(gè)殘疾皇子馁痴,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,037評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 作者:Natasha,原文鏈接肺孤,原文日期:2016-03-29譯者:bestswifter罗晕;校對(duì):shanks;定...
    梁杰_numbbbbb閱讀 492評(píng)論 0 3
  • 發(fā)現(xiàn) 關(guān)注 消息 iOS 第三方庫赠堵、插件小渊、知名博客總結(jié) 作者大灰狼的小綿羊哥哥關(guān)注 2017.06.26 09:4...
    肇東周閱讀 12,105評(píng)論 4 62
  • 如果你想跑10000米 你得先跑過5000米 如果你想跑5000米 你得先跑過2000米 如果你想跑2000米 你...
    不想起個(gè)帥氣的昵稱閱讀 431評(píng)論 1 1
  • 參加了由華宏汽車集團(tuán)組織,王坤老師主講的《有效演講藝術(shù)》培訓(xùn)后顾腊,從2017年6月28日開始第一階段訓(xùn)練粤铭,截止今日挖胃,...
    興宇閱讀 145評(píng)論 0 0
  • 信任杂靶,基本的信任 相信一種馴順的人類 相信一種高尚的動(dòng)物 如果貶低自己有好處 我一定會(huì)這么做的 我明白,我的價(jià)值 ...
    彭先生10閱讀 271評(píng)論 0 0