Swift 中的 Extension

刚用swift写项目,看别人的代码中大量用到Extension,于是很好奇什么时候用Extension,为什么这么频繁!
大量使用 extension 的主要目的是为了提高代码可读性。以下使用extension 的场景,尽管 extension 并非是为这些场景设计的。

私有的辅助函数

在Objectibve-C中,我们有.h文件和.m文件.同时管理这两个文件(以及在工程中有双倍的文件)是一件很麻烦的事情,好在我们只是快速浏览.h文件就知道这个类对外暴露的API,而内部的信息则被保存在.m文件中.在Swift中我们只有一个文件.

为了一眼就看出一个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使我们的代码结构变得更加清晰整洁.

这样一个很长的extension也为日后重构代码打下了良好的基础. 我们有可能吧这段逻辑抽取到一个单独的结构体中,尤其是当这个属性字符串可能在别的地方被用到时.但在编程时把这段代码放在私有的extension里面是一个良好的开始

分组

最初开始使用extension的真正原因是在swift刚诞生时,无法使用pragma标记(译注: Objective-C中的#paragma mark)

一般会用一个extension存放ViewController或者AppDelegate中所有初始化UI的函数,比如

private  extension AppDelegate {
    func configureAppStyling() {
       styleNavigationBar()
        styleBarButtons()
    }
    
    func styleNavigationBar() {
        UINavigationBar.appearance().barTintColor = UIColor.yellow
        UINavigationBar.appearance().tintColor = UIColor.red
        UINavigationBar.appearance().titleTextAttributes = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 19.0), NSAttributedString.Key.foregroundColor : UIColor.black]

    }
    
    func styleBarButtons() {
        let barButtonTextAttributes = [NSAttributedString.Key.font : UIFont.boldSystemFont(ofSize: 17.0), NSAttributedString.Key.foregroundColor : UIColor.black]
        
        UIBarButtonItem.appearance().setTitleTextAttributes(barButtonTextAttributes, for: .normal)
        
    }
}

或者把所有和通知相关的逻辑放到一起

extension MyViewController {
    
    func addNotigicationObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(oneNotifyEvent), name: NSNotification.Name(rawValue: "oneNotifyEvent"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(twoNotifyEvent), name: NSNotification.Name(rawValue: "twoNotifyEvent"), object: nil)
    }
    
    @objc func oneNotifyEvent() { }
    
    @objc func twoNotifyEvent(){   }
}

遵守协议

这是一种特殊的分组,我会把所有用来实现某个协议的方法放到一个extension中,在Objective-C中,习惯采用pragma标记

extension MyViewController: UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 5;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50.0
    }
}

模型(model)

这是一种在使用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())

// Get first letter of the first word
if let firstName = nameComponents.first, let firstCharacter = firstName.characters.first {
initials.append(firstCharacter)
}

// Get first letter of the last word
if nameComponents.count > 1 {
if let lastName = nameComponents.last, let firstCharacter = lastName.characters.first {
initials.append(firstCharacter)
}
}

return initials
}
}

借鉴原文: https://juejin.im/post/5a309c4bf265da4310485d75

猜你喜欢

转载自blog.csdn.net/weixin_34090643/article/details/86972104
今日推荐