0

How can I do a simple index into an array using enums in Swift?

I am a C programmer trying to understand Swift. 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.

3
  • let ix = Ptr.first.rawValue Commented Jul 6, 2019 at 23:20
  • enum Ptr: Int { case first, second, third } let arr = ["2.16", "4.3", "0.101"] let ix: Ptr = .first print (ix) let e = Double(arr[ix.rawValue]) Commented Jul 6, 2019 at 23:46
  • Thank you. Coming from decades of C programming, Swift is quite counterintuitive. Commented Jul 7, 2019 at 18:33

1 Answer 1

2

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). So in order to get 0 you need to access the case's rawValue property which is an Int:

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

Hope that helps!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Why couldn't Apple just stick to C?
Well, swift is a really powerful language. I think you will really like it if you get familiar with the language.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.