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