在Swift中调用函数内部的枚举

时间:2017-03-30 03:29:44

标签: swift

我绝对不知所措。我的导师在寻找什么?有什么建议吗?

开始这样的事情,但我刚刚离开..

enum Color: String {

case blue = "orange"
case red = "green"
case yellow = "purple"

}


func complement(_ color) -> String {
    case
}

问题: 使用三种基色和三种辅助颜色创建一个类型Color。然后创建一个函数complement,它将返回所提供颜色的补色。

Red's complement is green
Blue's complement is orange
Yellow's complement is purple

complement(.red) -> .green
complement(.orange) -> .blue

更新

enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func compliment(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    break
    }
}

let red = Color.red
let compliment = compliment(red)
print(compliment)

let green = Color.green
let compliment = compliment(green)
print(compliment)

let blue = Color.blue
let compliment = compliment(blue)
print(compliment)
  

错误:在其自己的初始值中使用的变量

let compliment = compliment(red)

它为每个实例执行此操作

2 个答案:

答案 0 :(得分:0)

由于这是作业,我会给你足够的指针让你开始,但不会为你做。

enum Color: String {
    case red = "red"
    case green = "green"
    case blue = "blue"

    case yellow = "yellow"
    case orange = "orange"
    case purple = "purple"
}

func complement(_ color: Color) -> Color {
    switch color {
    case .red: return .green
    case .green: return .red
    case .blue: return .orange
    // etc.
    }
}

let red = Color.red
let compliment = complement(red)
print(compliment)

在没有深入色彩理论的情况下,红色的补充不是蓝色 - 它是青色的。对于绿色它的洋红色。而蓝色的补充是黄色的。

答案 1 :(得分:0)

这更通用。您不必创建具有明确String的类型。

enum Color {
    case red
    case green
    case blue

    case orange
    case yellow
    case violet
}

func complement(_ color: Color) -> Color {
    switch color {

    case .red: return .green
    case .green: return .red

    case .blue: return .orange
    case .orange: return .blue

    case .yellow: return .violet
    case .violet: return .yellow

    }
}

let red = Color.red
let redComplement = complement(red)
print("Complement of \(red) is \(redComplement)")

let green = Color.green
let greenComplement = complement(green)
print("Complement of \(green) is \(greenComplement)")