做者:Natasha,原文連接,原文日期:2016-03-29
譯者:bestswifter;校對:shanks;定稿:Channe編程
別人一看到個人 Swift 代碼,馬上就會問我爲何如此頻繁的使用 extension。這是前幾天在我寫的另外一篇文章中收到的評論:swift
我大量使用 extension 的主要目的是爲了提升代碼可讀性。如下是我喜歡使用 extension 的場景,儘管 extension 並不是是爲這些場景設計的。app
在 Objective-C 中,咱們有 .h 文件和 .m 文件。同時管理這兩個文件(以及在工程中有雙倍的文件)是一件很麻煩的事情,好在咱們只要快速瀏覽 .h 文件就能夠知道這個類對外暴露的 API,而內部的信息則被保存在 .m 文件中。在 Swift 中,咱們只有一個文件。async
爲了一眼就看出一個 Swift 類的公開方法(能夠被外部訪問的方法),我把內部實現都寫在一個私有的 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 區隔開來 // 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 使個人代碼結構變得更加清晰整潔。post
這樣一個很長的 extension 也爲往後重構代碼打下了良好的基礎。咱們有可能把這段邏輯抽取到一個單獨的結構體中,尤爲是當這個屬性字符串可能在別的地方被用到時。但在編程時把這段代碼放在私有的 extension 裏面是一個良好的開始。ui
我最初開始使用 extension 的真正緣由是在 Swift 剛誕生時,沒法使用 pragma 標記(譯註:Objective-C 中的 #pragma mark)。是的,這就是我在 Swift 剛誕生時想作的第一件事。我使用 pragma 來分割 Objective-C 代碼,因此當我開始寫 Swift 代碼時,我須要它。this
因此我在 WWDC Swift 實驗室時詢問蘋果工程師如何在 Swift 中使用 pragma 標記。和我交流的那位工程師建議我使用 extension 來替代 pragma 標記。因而我就開始這麼作了,而且馬上愛上了使用 extension。spa
儘管 pragma 標記(Swift 中的 //MARK)很好用,但咱們很容易忘記給一段新的代碼加上 MARK 標記,尤爲是你處在一個具備不一樣代碼風格的小組中時。這每每會致使若干個無關函數被放在了同一個組中,或者某個函數處於錯誤的位置。因此若是有一組函數應該寫在一塊兒,我傾向於把他們放到一個 extension 中。翻譯
通常我會用一個 extension 存放 ViewController 或者 AppDelegate 中全部初始化 UI 的函數,好比:
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) } } }
這是一種特殊的分組,我會把全部用來實現某個協議的方法放到一個 extension 中。在 Objective-C 中,我習慣使用 pragma 標記。不過我喜歡 extension 更加完全的分割和更好的可讀性:
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 協議實現 extension TodoItemViewModel: ImageWithTextCellDataSource { var imageName: String { return item.completed ? "checkboxChecked" : "checkbox" } var attributedText: NSAttributedString { return itemContent } }
這種方法一樣很是適用於分割 UITableViewDataSource 和 UITableViewDelegate 的代碼:
// MARK: 表格視圖數據源 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] } }
這是一種我在使用 Objective-C 操做 Core Data 時就喜歡採用的方法。因爲模型發生變化時,Xcode 會生成相應的模型,因此函數和其餘的東西都是寫在 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 } }
儘管這些用法可能不那麼「傳統」,但 Swift 中 extension 的簡單使用,可讓代碼質量更高,更具可讀性。
本文由 SwiftGG 翻譯組翻譯,已經得到做者翻譯受權,最新文章請訪問 http://swift.gg。