简体   繁体   English

Swift枚举作为数组的索引

[英]Swift enums as index to an array

How can I do a simple index into an array using enums in Swift? 如何在Swift中使用枚举在数组中建立简单索引?

I am a C programmer trying to understand Swift. 我是一名试图理解Swift的C程序员。 This is perplexing. 这令人困惑。

var  arr: [String] = ["2.16", "4.3", "0.101"]

enum Ptr: Int {
    case first = 0
    case second = 1
    case third = 2    
}

var ix = Int(Ptr.first)
print (ix)
let e = Double (arr[ix])

` `

I would expect that Ptr.first would yield a 0 integer which I could as an index into array arr. 我希望Ptr.first会产生一个0整数,我可以作为数组arr的索引。

Why it doesn't work is because all cases in your enum (first, second, third) are essentially of type Ptr (the type of your enum). 之所以不起作用,是因为枚举中的所有情况(第一,第二,第三)基本上都是Ptr类型(枚举的类型)。 So in order to get 0 you need to access the case's rawValue property which is an Int: 因此,为了获得0,您需要访问案例的rawValue属性,它是一个Int:

var ix = Ptr.first.rawValue //accessing the case's rawValue property
print (ix)
let e = Double (arr[ix])

Hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM