xcode - Swift 编程语言枚举实验

标签 xcode enums swift

我正在阅读《The Swift Programming Language》这本书,但我被困在了一个实验中。

我得到了这个代码:

enum Rank: Int {
    case Ace = 1
    case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
    case Jack, Queen, King
    func simpleDescription() -> String {
        switch self {
        case .Ace:
            return "Ace"
        case .Jack:
            return "Jack"
        case .Queen:
            return "Queen"
        case .King:
            return "King"
        default:
            return String(self.toRaw())
        }
    }
}

对于实验,我必须“编写一个函数,通过比较两个 Rank 值的原始值来比较它们。”

我试了一下:

func rankCompare(first: String, second: String) -> String {
    let firstRank = Rank.first
}

但我最终遇到了错误,因为我不知道如何传递枚举值。

有人可以帮忙吗?

最佳答案

枚举值可以像其他类型一样传递。以下函数是 Rank 枚举的一部分,并将一个 Rank 与另一个进行比较。

func compareToOther(other:Rank) -> Bool {    // other is of type Rank 
        return self.toRaw() == other.toRaw()
}

这是快速实现和使用的屏幕截图。 enter image description here

关于xcode - Swift 编程语言枚举实验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24147060/

相关文章:

iphone - iOS : Cancel a Void function

xcode - ffmpeg : Is this a bug in Xcode?

swift - SpriteKit Swift 使整个场景变暗,然后再改回来

ios - 如何根据 i18n 将 NSTimeInterval 正确格式化为时间段?

xcode - 从 swift osx 应用程序发送电子邮件

xcode - PerformSegueWithIdentifier 未进行转换

Scala 枚举 - 如何分配初始值?

ruby-on-rails - 从 Rails 4.1 中的选择中保存枚举

c++ 将枚举值标记为已弃用?

ios - 在 Decodable 协议(protocol)中为模型数组设置容量