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

如何用Swift结构体和Computed Property根据RGB值确定颜色名称

问题分析
  • 现有代码的colourName为存储属性,需要实例化时手动传入,没有实现「根据red、green、blue三个RGB分量自动计算颜色名称」的核心需求
  • 计算属性chosenColour仅做了字符串拼接,没有关联RGB判断逻辑
修复后代码
struct Colour {
    var red: Int
    var green: Int
    var blue: Int
    
    // 计算属性:根据RGB分量自动返回对应的颜色名称
    var colourName: String {
        // 可根据需求扩展更多颜色匹配规则
        switch (red, green, blue) {
        case (255, 255, 255): return "White"
        case (0, 0, 0): return "Black"
        case (255, 0, 0): return "Red"
        case (0, 255, 0): return "Green"
        case (0, 0, 255): return "Blue"
        case (255, 255, 0): return "Yellow"
        default: return "Unknown Colour"
        }
    }
    
    var chosenColour: String {
        return "The colour is \(colourName)"
    }
}

// 实例化时仅需传入RGB值,无需手动传colourName
var colour = Colour(red: 255, green: 255, blue: 255)
print(colour.chosenColour) // 输出:The colour is White
修复说明
  • 将原本的存储属性colourName改为计算属性,内部通过switch匹配RGB三元组的值,自动返回对应的颜色名称,无需手动传入
  • 实例化结构体时仅需要传入red、green、blue三个参数即可,colourName会自动计算生成
  • 可根据实际需求在switch的case中扩展更多颜色的RGB匹配规则

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 21:54:02