在swift 4.0中使用枚举为数组下标
iOS 11.x Swift 4.0 这不会编译,因为您不能用emum为数组下标,看起来是这样吗?有没有一种我可以用的可以用的在swift 4.0中使用枚举为数组下标,swift,struct,enums,Swift,Struct,Enums,iOS 11.x Swift 4.0 这不会编译,因为您不能用emum为数组下标,看起来是这样吗?有没有一种我可以用的可以用的 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]
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)")
您应该使用rawValue而不是enum实例本身,例如cord[axis.x.rawValue]而不是cord[axis.x]。阅读更多信息。您可以通过向数组添加扩展来实现,但这是您可以做的事情,而不是您应该做的事情
extension Array {
subscript(index: axis) -> Element {
return self[index.rawValue]
}
}
您应该做的是定义适当的数据结构来封装数据:
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())")
使用axis.x.rawValueThank,这非常有效!
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())")