Swift 分类的使用

秦皓君
2023-12-01

在oc中为了增强已有类的功能,我们经常使用分类。使用分类,我们可以在不破坏原有类的结构的前提下,对原有类进行模块化的扩展。但是在swift中没有分类这种写法了。相对应的是swift中只有扩展(Extensions)。扩展就是向一个已有的类、结构体、枚举类型或者协议类型添加新功能(functionality)。扩展和 Objective-C 中的分类类似。(不过与 Objective-C 不同的是,Swift 的扩展没有名字。)

一、如何创建Swift的拓展类

1、创建一个普通的Swift类,比如我现在想要创建一个关于日期的拓展类(NSDate+Helper.swift)

2、创建好之后,添加如下代码:

import Foundation
import UIKit

extension NSDate {
    
   class func stringWithFormat(format:String, date:Date) -> String
    {
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = format
        return dateFormatter.string(from: date)
    }
    
    class func yearIndex(date:Date) -> Int
    {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components = calendar.dateComponents(in: timeZone!, from: date)
        return components.year!
    }
    
    class func monthIndex(date:Date) -> Int
    {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components = calendar.dateComponents(in: timeZone!, from: date)
        return components.month!
    }
    
    class func daysOfMonth(date:Date) -> Int
    {
        let calendar = Calendar.current
        let range = calendar.range(of: Calendar.Component.day, in: Calendar.Component.month, for: date)
        return (range?.count)!
    }
    
    class func getWeekdayOfDate(date:Date) -> Int
    {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components = calendar.dateComponents(in: timeZone!, from: date)
        return components.weekday!-1 //从星期日开始,也就是星期天是1 星期一是2 ……星期六是7
    }
    
    class func isSameDay(date1:Date, date2:Date) -> Bool
    {
        let calendar = Calendar.current
        let timeZone = TimeZone.init(identifier: "UTC")
        let components1 = calendar.dateComponents(in: timeZone!, from: date1)
        let components2 = calendar.dateComponents(in: timeZone!, from: date2)

        return components1.year == components2.year && components1.month == components2.month && components1.day == components2.day
    }
    
    class func getDateWithYear(year:Int, month:Int, day:Int) -> Date
    {
        var components = DateComponents.init()
        components.year = year
        components.month = month
        components.day = day
        
        let calendar = Calendar.current
        let date = calendar.date(from: components)
        return date!
    }
    
   
}

3、如何使用拓展类的方法

Swift不需要导入头文件,直接可以使用

let currentDate = NSDate.getDateWithYear(year: currentYear, month: currentMonth, day: 1)

let firstDay = NSDate.getWeekdayOfDate(date: currentDate)
        
let totalDays = NSDate.daysOfMonth(date: currentDate)

 

 类似资料: