Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum to subscript an array in swift 4.0

iOS 11.x Swift 4.0

This doesn't compile cause you cannot subscript an array with an emum it seems? Is there a type I can use that will work?

enum axis:Int {
  case x = 0
  case y = 1
}

var cords = [[10,21],[23,11],[42,12],[31,76]]
var smallestCord:Int = Int.max
var smallestSet:[Int] = []
for cord in cords {
  if cord[axis.x] < smallestCord {
    smallestCord = cord[axis.x]
    smallestSet = cord
  }
}
print("\(smallestCord) \(smallestSet)")

Got it work with a static var like this? but can I make an enum work?

private struct axis {
  static let x = 0
  static let y = 1
}
like image 645
user3069232 Avatar asked Feb 27 '26 17:02

user3069232


2 Answers

You can by adding an extension to Array, but this is a case of "what you could do" rather than "what you should do"

extension Array {
    subscript(index: axis) -> Element {
        return self[index.rawValue]
    }
}

What you should do instead is to define proper data structures to encapsulate your data:

struct Point {
    var x: Int
    var y: Int

    // For when you need to convert it to array to pass into other functions
    func toArray() -> [Int] {
        return [x, y]
    }
}

let cords = [
    Point(x: 10, y: 21),
    Point(x: 23, y: 11),
    Point(x: 42, y: 12),
    Point(x: 31, y: 76)
]
let smallestSet = cords.min(by: { $0.x < $1.x })!
let smallestCord = smallestSet.x
print("\(smallestCord) \(smallestSet.toArray())")
like image 120
Code Different Avatar answered Mar 02 '26 06:03

Code Different


You should use rawValue instead of an enum instance itself, e.g cord[axis.x.rawValue] instead of cord[axis.x]. Read more about it here.

like image 41
Yury Fedorov Avatar answered Mar 02 '26 07:03

Yury Fedorov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!