Swe*_*per 8 multidimensional-array swift
假设我有这个数组:
let a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Run Code Online (Sandbox Code Playgroud)
现在我想要这样的东西:
public func indicesOf(x: Int, array: [[Int]]) -> (Int, Int) {
...
}
Run Code Online (Sandbox Code Playgroud)
所以我可以这样称呼它:
indicesOf(7, array: a) // returns (2, 0)
Run Code Online (Sandbox Code Playgroud)
当然,我可以使用:
for i in 0..<array.count {
for j in 0..<array[i].count {
if array[i][j] == x {
return (i, j)
}
}
}
Run Code Online (Sandbox Code Playgroud)
但这甚至不是很接近!
我想要一种方法来做到这一点很快乐.我想也许我可以使用reduce或map?
Mar*_*n R 12
您可以使用enumerate()和简化代码indexOf().此函数还应返回一个可选元组,因为该元素可能不存在于"矩阵"中.最后,你可以使它通用:
func indicesOf<T: Equatable>(x: T, array: [[T]]) -> (Int, Int)? {
for (i, row) in array.enumerate() {
if let j = row.indexOf(x) {
return (i, j)
}
}
return nil
}
Run Code Online (Sandbox Code Playgroud)
您也可以使它成为一个嵌套在扩展Array的Equatable
要素:
extension Array where Element : CollectionType,
Element.Generator.Element : Equatable, Element.Index == Int {
func indicesOf(x: Element.Generator.Element) -> (Int, Int)? {
for (i, row) in self.enumerate() {
if let j = row.indexOf(x) {
return (i, j)
}
}
return nil
}
}
if let (i, j) = a.indicesOf(7) {
print(i, j)
}
Run Code Online (Sandbox Code Playgroud)
斯威夫特3:
extension Array where Element : Collection,
Element.Iterator.Element : Equatable, Element.Index == Int {
func indices(of x: Element.Iterator.Element) -> (Int, Int)? {
for (i, row) in self.enumerated() {
if let j = row.index(of: x) {
return (i, j)
}
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
接受闭包的版本,类似于index(where :),因此它可以在任何元素的数组上使用,不仅Equatable
extension Array where Element : Collection, Element.Index == Int {
func indices(where predicate: (Element.Iterator.Element) -> Bool) -> (Int, Int)? {
for (i, row) in self.enumerated() {
if let j = row.index(where: predicate) {
return (i, j)
}
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
像这样使用:
let testArray = [[1,2,3], [4,5,6], [7,8]]
let testNumber = 6
print(testArray.indices(of: testNumber))
print(testArray.indices{$0 == testNumber})
Optional((1, 2))
Optional((1, 2))
Run Code Online (Sandbox Code Playgroud)
另外,它可以与IndexPath:
extension Array where Element : Collection, Element.Index == Int {
func indexPath(where predicate: (Element.Iterator.Element) -> Bool) -> IndexPath? {
for (i, row) in self.enumerated() {
if let j = row.index(where: predicate) {
return IndexPath(indexes: [i, j])
}
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)