iOS | 封装一个搜索记录管理类

搜索记录

项目中经常遇到的功能,简单封装一下:

import Foundation

/// 搜索记录管理类
struct RecordsManager {
    
    private static let key = "records_key"
    private static let maxRecordsCount = 10
    private static var records: [String] {
        get {
            UserDefaults.standard.value(forKey: key) as? [String] ?? []
        }
        set {
            UserDefaults.standard.setValue(newValue, forKey: key)
            UserDefaults.standard.synchronize()
        }
    }
    
    /// 添加一条记录
    @discardableResult
    static func addItem(_ item: String) -> [String] {
        // 移除已有相同记录
        records = records.filter { (str) -> Bool in
            str != item
        }
        // 添加到头部
        records.insert(item, at: 0)
        // 最多存10条
        if records.count > maxRecordsCount {
            records.removeLast()
        }
        return records
    }
    
    ///删除一条记录
    @discardableResult
    static func deleteItem(_ item: String) -> [String] {
        records = records.filter({ (str) -> Bool in
            str != item
        })
        return records
    }
    
    /// 获取所有记录
    static func getAll() -> [String] {
        records
    }
    
    /// 清空
    @discardableResult
    static func clear() -> [String] {
        records = []
        return records
    }
    
}

使用如下:

@IBAction func addButtonClicked(_ sender: Any) {
    print(RecordsManager.addItem(textField.text!))
}

@IBAction func clearButtonClicked(_ sender: Any) {
    print(RecordsManager.clear())
}

@IBAction func printButtonClicked(_ sender: Any) {
    print(RecordsManager.getAll())
}

@IBAction func deleteButtonClicked(_ sender: Any) {
    print(RecordsManager.deleteItem(textField.text!))
}

推荐阅读更多精彩内容