2017-09-14 212 views
0

继承人我试图教我自己。我想要一双在嵌套indexArray元件的指向numberArray内部元件:非嵌套数组嵌套数组Swift

IOW:IF indexArray具有[[0,2],[3,4]]我想要的嵌套元素在numberArray

朝向元件 #0numberArray #2和元件3和4点
func findNumIndex(numberArray: [Int], indexArray: [[Int]]) -> Int { 
     // Use the NESTED index elements to arrive at element index in numberArrray 
    } 

    findNumIndex(nums: [0,1,2,3,4,5,6,7,8,9], queries: [[0,1],[1,2],[3,4]]) 

    // We would look at index 0 and 1, index 1 and 2, index 3 and 4 and get the numbers/ 

起初我想平坦化数组,但这不是我想要的。

回答

2

这似乎是东西,你可以用一个简单的map做:

indexArray.map { $0.map { numberArray[$0] } } 
+0

Annnnnd我仍然在赚钱......哈哈! –

+1

没有错。我的建议:阅读'map','flatMap','reduce'和'filter'方法。它们在很多情况下非常有用! –

0

超过设计了一下,不过这件事是在很多情况下,一个非常方便的扩展:

extension RandomAccessCollection where Self.Index == Int { 
    subscript<S: Sequence>(indices indices: S) -> [Self.Element] 
     where S.Iterator.Element == Int { 
     return indices.map{ self[$0] } 
    } 
} 

let input = ["a", "b", "c", "d", "e"] 
let queries = [[0, 1], [1, 2], [3, 4]] 
let result = queries.map{ input[indices: $0] } 

print(result) // => [["a", "b"], ["b", "c"], ["d", "e"]] 
+0

这很酷!谢谢大家!我有一些好东西可以咀嚼。 –