“錯誤”的使用 Swift 中的 Extension

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

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

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

私有的輔助函數(shù)

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

為了一眼就看出一個 Swift 類的公開方法(可以被外部訪問的方法),我把內部實現(xiàn)都寫在一個私有的 extension 中,比如這樣:
// 這樣可以一眼看出來,這個結構體中,那些部分可以被外部調用

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
    }
}

// 把所有內部邏輯和外部訪問的 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)
   }
}

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

分組

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

或者把所有和通知相關的邏輯放到一起:

extension TodoListViewController {

// 初始化時候調用
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: 響應列選擇
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 會生成相應的模型,所以函數(shù)和其他的東西都是寫在 extension 或者 category 里面的。

在 Swift 中,我盡可能多的嘗試使用結構體,但我依然喜歡使用 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 的簡單使用,可以讓代碼質量更高,更具可讀性。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

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