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