“錯誤”的使用 Swift 中的 Extension

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

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

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

私有的輔助函數(shù)

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

為了一眼就看出一個 Swift 類的公開方法(可以被外部訪問的方法),我把內(nèi)部實現(xiàn)都寫在一個私有的 extension 中,比如這樣:
// 這樣可以一眼看出來,這個結(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)
   }
}

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

分組

我最初開始使用 extension 的真正原因是在 Swift 剛誕生時,無法使用 pragma 標(biāo)記(譯注:Objective-C 中的 #pragma mark)。是的,這就是我在 Swift 剛誕生時想做的第一件事。我使用 pragma 來分割 Objective-C 代碼,所以當(dāng)我開始寫 Swift 代碼時,我需要它。
所以我在 WWDC Swift 實驗室時詢問蘋果工程師如何在 Swift 中使用 pragma 標(biāo)記。和我交流的那位工程師建議我使用 extension 來替代 pragma 標(biāo)記。于是我就開始這么做了,并且立刻愛上了使用 extension。
盡管 pragma 標(biāo)記(Swift 中的 //MARK)很好用,但我們很容易忘記給一段新的代碼加上 MARK 標(biāo)記,尤其是你處在一個具有不同代碼風(fēng)格的小組中時。這往往會導(dǎo)致若干個無關(guān)函數(shù)被放在了同一個組中,或者某個函數(shù)處于錯誤的位置。所以如果有一組函數(shù)應(yīng)該寫在一起,我傾向于把他們放到一個 extension 中。
一般我會用一個 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 {

// 初始化時候調(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é)議實現(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 時就喜歡采用的方法。由于模型發(fā)生變化時,Xcode 會生成相應(yīng)的模型,所以函數(shù)和其他的東西都是寫在 extension 或者 category 里面的。

在 Swift 中,我盡可能多的嘗試使用結(jié)構(gòu)體,但我依然喜歡使用 extension 將 Model 的屬性和基于屬性的計算分割開來。這使 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())
    
    // 得到第一個單詞的第一個字母
    if let firstName = nameComponents.first, let firstCharacter = firstName.characters.first {
        initials.append(firstCharacter)
    }
    
    // 得到最后一個單詞的第一個字母
    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)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,443評論 6 532
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,530評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,407評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,981評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,759評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,204評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,263評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,415評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,955評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,650評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,892評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,675評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,967評論 2 374

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

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