简体   繁体   English

斯威夫特:搜索在数组中包含数字的数组索引的更好方法?

[英]Swift: Better way to search for the index of an array containing a number inside an array?

Curious to know if there is a better way to do this. 想知道是否有更好的方法可以做到这一点。 I have an array of arrays that contain integers. 我有一个包含整数的数组的数组。 All the integers are unique. 所有整数都是唯一的。 I want to search for a given number and return the index of the first array. 我想搜索给定的数字并返回第一个数组的索引。 I don't care what the index is of the array containing the numbers. 我不在乎包含数字的数组的索引是什么。

This does what I want but I'm new to swift and figured there is a better way. 这是我想要的,但是我是新手,因此发现有更好的方法。

let arr:[[Int]] = [[0], [1], [2, 3], [4], [11, 12, 13, 14, 15, 16], [5], [6], [7], [8], [9], [10]]

var t = -1
for q in arr {
    t += 1
    if let x = q.index(of: 13) { // <-- looking for the index that contains 13
        print ("t: \(t)") // <-- this is what I want. Returns '4'
    }
}

Here's one way: 这是一种方法:

let arr: [[Int]] = [[0], [1], [2, 3], [4], [11, 12, 13, 14, 15, 16], [5], [6], [7], [8], [9], [10]]

for (i, a) in arr.enumerated() {
    if let _ = a.index(of: 13) {
        print(i)
    }
}

It makes use of the enumerated() method of collections. 它利用了集合的enumerated()方法。 It returns a tuple containing the index of the array i and the actual element of the array a . 它返回一个包含该阵列的索引的元组i和阵列的实际元素a

Using functional programming 使用函数式编程

Here's the functional programming version if that's more your style: 如果您更喜欢这种风格,请参见下面的函数式编程版本:

arr.enumerated().map { $0 }.map { i, a in
    if let _ = a.index(of: 13) { 
        print(i) 
    }
}

A solution without loop using index(where: 使用index(where:无循环解决方案index(where:

let arr: [[Int]] = [[0], [1], [2, 3], [4], [11, 12, 13, 14, 15, 16], [5], [6], [7], [8], [9], [10]]

if let index = arr.index(where: { $0.contains(13) }) {
    print(index)
} else {
    print("not found")
}

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

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