2017-08-29 5 views
0

I持って私の遊び場で、次のコード:インデックス/コレクション

let array = [3,3] 
let first = array.first! 
let last = array.last! 

let indices = [array.index(of: first)!, array.index(of: last)!] 
print(indices) // This prints [0,0] 

私は「インデックス(の:)」方法だけ配列から最初に一致するインスタンスをつかむことを理解し、これはより効率的ですが、私は "array.last"から値を得ているという事実に基づいて最後のインデックスを取得する方法があるのだろうかと思います。

は、私は以下の持っていた場合にはさらに、:

let lotsOfThrees = [3,3,3,3,3,3,3] 
let fourthThree = lotsOfThrees[3] 
// Write code to return the index of "fourthThree" (possibly based on memory address) 

をメモリアドレスに基づいてこれを行う方法がある場合、私は思ったんだけど、正直なところわかりません。

+0

私はあなたがやろうとしているのか理解していません。 "fourthThree"のインデックスは "3"です - あなたはすでにそれを持っています。同様に、最初のコードでは、最初の3のインデックスは '0'で、最後のインデックスは' array.count-1'です。 '3'は値なので、配列には特定の" 3 "はありません。彼らはすべて同じです。 – Paulw11

+0

まあ、私は参照をつなぎ合わせる方法があるのだろうかと思っています。他の操作を実行したり、これらの値を関数に渡して、 "fourthThree"がインデックス3であることがわからない場合は、メモリアドレスが3であることがわかります。 "lotsOfThrees"配列の4番目のオブジェクトにそれを関連付ける方法はありますか?ライブラリー機能を使用することが好ましい。私は基本的にarray.lastを渡して、array.firstと同じ値を持っているかどうかを区別できるライブラリ関数があるかどうかを知りたがっています。 – RDSpinz

+1

なぜこれが必要ですか?あなたは実際にこれで解決しようとしている問題は何ですか? – rmaddy

答えて

0

最後の要素のインデックスを逆にして、のインデックスが最初にになるようにすることができます。元の配列の最後の要素のインデックスは、(逆配列で最初に出現するインデックス) - (配列のサイズ) - 1です。

extension Array<T> { 
    func lastIndex(of item: T) -> Int? { 
     if let lastIndex = self.reverse().index(of: item) { 
      return self.count() - lastIndex - 1 
     } else { 
      return nil 
     } 
    } 
} 
0

私はあなたが探している値でインデックスをペアリングするenumerated()filterを使用することをお勧めします:

let lotsOfThrees = [3, 3, 3, 3, 3, 3, 3] 
let threesAndIndices = lotsOfThrees.enumerated().filter { $1 == 3 } 
print(threesAndIndices) 
[(offset: 0, element: 3), (offset: 1, element: 3), (offset: 2, element: 3), (offset: 3, element: 3), (offset: 4, element: 3), (offset: 5, element: 3), (offset: 6, element: 3)] 
// find index of last three 
print(threesAndIndices.last!.offset) 
6 
// find index of 4th three 
print(threesAndIndices[4 - 1].offset) 
3 

あなたは配列のサイズをチェックして、このような最後の値があることを仮定するべきではありません。

let values = [1, 3, 2, 4, 1, 3, 3, 4, 1] 
let threesAndIndices = values.enumerated().filter { $1 == 3 } 

// find index of last three 
if let last = threesAndIndices.last { 
    print("index of last three is \(last.offset)") 
} else { 
    print("there are no threes") 
} 
index of last three is 6 
// find index of 4th three 
let nth = 4 
if nth > threesAndIndices.count { 
    print("there aren't \(nth) threes") 
} else { 
    let index = threesAndIndices[nth - 1].offset 
    print("the index of three #\(nth) is \(index)") 
} 
は、
there aren't 4 threes