You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免操作Codable结构体Favorites时重复写favorites.favorites?

解决Favorites结构体调用重复命名的问题

这里有几种实用的方法可以避免favorites.favorites这种重复书写的情况:

  • 添加便捷操作方法
    在结构体里封装直接操作内部数组的方法,调用时更直观:
struct Favorites: Codable {
    var favorites: [String]
    
    // 添加单个元素
    mutating func add(_ phrase: String) {
        favorites.append(phrase)
    }
    
    // 添加多个元素
    mutating func addAll(_ phrases: [String]) {
        favorites.append(contentsOf: phrases)
    }
}

使用示例:

var myFavorites = Favorites(favorites: ["apple"])
myFavorites.add("banana")
myFavorites.addAll(["orange", "grape"])
  • 代理数组的原生方法(遵循MutableCollection协议)
    让结构体遵循MutableCollection,把内部数组的接口暴露出来,这样就能直接使用数组的所有原生方法:
struct Favorites: Codable, MutableCollection {
    var favorites: [String]
    
    // 实现Collection协议的必要属性
    var startIndex: Int { favorites.startIndex }
    var endIndex: Int { favorites.endIndex }
    
    subscript(position: Int) -> String {
        get { favorites[position] }
        set { favorites[position] = newValue }
    }
    
    func index(after i: Int) -> Int {
        favorites.index(after: i)
    }
}

使用示例:

var myFavorites = Favorites(favorites: ["apple"])
myFavorites.append("banana") // 直接用数组的append
myFavorites.insert("pear", at: 0) // 直接用数组的insert
myFavorites.remove(at: 1) // 直接用数组的remove
  • 重载+=操作符
    直接给结构体重载+=操作符,支持直接添加单个元素或数组:
struct Favorites: Codable {
    var favorites: [String]
}

// 重载+=支持添加单个元素
extension Favorites {
    static func += (lhs: inout Favorites, rhs: String) {
        lhs.favorites.append(rhs)
    }
    
    // 重载+=支持添加数组
    static func += (lhs: inout Favorites, rhs: [String]) {
        lhs.favorites += rhs
    }
}

使用示例:

var myFavorites = Favorites(favorites: ["apple"])
myFavorites += "banana"
myFavorites += ["orange", "grape"]
  • 重命名内部属性
    最直接的方式,把内部数组的名字改成和结构体不重复的,比如items:
struct Favorites: Codable {
    var items: [String]
}

调用时就变成myFavorites.items += [phrase],虽然还是两层访问,但避免了名字重复的冗余感。

内容的提问来源于stack exchange,提问作者Daan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 16:42:51