使用NSLog记录Swift枚举

zou*_*oul 22 nslog swift

我正在尝试记录枚举:

enum CKAccountStatus : Int {
    case CouldNotDetermine
    case Available
    case Restricted
    case NoAccount
}

NSLog("%i", CKAccountStatus.Available)
Run Code Online (Sandbox Code Playgroud)

编译器抱怨:

Type 'CKAccountStatus' does not conform to protocol 'CVarArg'
Run Code Online (Sandbox Code Playgroud)

为什么?我试图抛出价值:

NSLog("%i", CKAccountStatus.Available as Int)
Run Code Online (Sandbox Code Playgroud)

但这也不会飞:

Cannot convert the expression's type '()' to type 'String'
Run Code Online (Sandbox Code Playgroud)

ric*_*ter 28

得到枚举的基本Int价值:CKAccountStatus.Available.rawValue.

枚举在Swift中不是严格的整数,但是如果它们被声明为底层类型,你可以得到它rawValue- 无论底层类型是什么.(enum Foo: String会为你提供字符串rawValue等)如果枚举没有基础类型,rawValue则没有什么可以给你.在从ObjC导入的API中,任何定义的枚举NS_ENUM都具有基础整数类型(通常Int).

如果您想更具描述性地打印任何枚举,可以考虑对采用该Printable协议的枚举类型进行扩展.

  • 使用`hashValue`会滥用API合约.`Hashable`类型要求`hashValue`对于"相等"值是相同的,否则是唯一的,但是没有其他保证......即使它巧合地返回与`Int`枚举类型的`rawValue`相同,你也不要不知道将来不会改变.最好选择记录下来的API来做你想做的事情. (2认同)

mat*_*att 7

枚举实际上是不透明的.它可能有原始值,你可以得到; 但许多枚举没有.(您不必将枚举声明为具有类型,如果不是,则没有原始值.)我要做的是给枚举一个description方法并明确地调用它.

区分枚举当前值的唯一方法是通过switch语句,因此您的description方法将处理每种情况,并且switch语句的每个case将返回不同的描述值.

enum Suit {
    case Hearts, Diamonds, Spades, Clubs
    func description () -> String {
        switch self {
        case Hearts:
            return "hearts"
        case Diamonds:
            return "diamonds"
        case Spades:
            return "spades"
        case Clubs:
            return "clubs"
        }
    }
}

var suit = Suit.Diamonds
println("suit \(suit.description())")  // suit diamonds
Run Code Online (Sandbox Code Playgroud)


Chr*_*ckx 5

这是我的方法:

enum UserMode : String
{
   case Hold = "Hold";
   case Selecting = "Selecting";
   case Dragging = "Dragging";
}
Run Code Online (Sandbox Code Playgroud)

然后,每当我需要打印原始值时:

//Assuming I have this declared and set somewhere
var currentMode: UserMode = .Selecting;
Run Code Online (Sandbox Code Playgroud)

NSLog("CurrentMode \(_currMode.rawValue)");
Run Code Online (Sandbox Code Playgroud)

将打印:

CurrentMode选择