var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
myArrayを最初の項目で並べ替える方法? 2番目の項目ですか?昇順ですか?降りる?すぐに配列の配列を並べ替える3
var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
myArrayを最初の項目で並べ替える方法? 2番目の項目ですか?昇順ですか?降りる?すぐに配列の配列を並べ替える3
お知らせ
多くのおかげで、そのインデックスは、実行時に致命的なエラーにつながる可能性があるものを、チェックされない範囲でした。 Alexandersのコメントをチェックしてください! :)
var myArray: [[String]] =
[
["1", "picture1.png", "John", "Smith"],
["2", "picture2.png", "Mike", "Rutherford"],
]
func sort<T: Comparable>(ArrayOfArrays: [[T]], sortingIndex: Int, sortFunc: (T, T) -> Bool)) -> [[T]] {
return ArrayOfArrays.sorted {sortFunc($0[sortingIndex], $1[sortingIndex])}
}
}
print(sort(ArrayOfArrays: myArray, sortingIndex: 0, sortFunc: <))
//[["1", "picture1.png", "John", "Smith"], ["2", "picture2.png", "Mike", "Rutherford"]]
print(sort(ArrayOfArrays: myArray, sortingIndex: 0, sortFunc: >))
//[["2", "picture2.png", "Mike", "Rutherford"], ["1", "picture1.png", "John", "Smith"]]
スイフトアレイには、組み込みのソート機能があります。ちょうどそれを呼び出します。
myArray[0].sort { $0.compare($1, options: .numeric) == .orderedAscending }
myArray[1].sort { $0.compare($1, options: .numeric) == .orderedDescending }
ありがとうございます。 –
私はあなたが一緒にこの関連データをパッケージ化するstruct
またはclass
を作成することをお勧め:
struct Person {
let id: Int
let picture: String // This should probably be a URL, NSImage or UIImage
let firstName: String
let lastName: String
}
をして、正しいタイプを使用してインスタンスを定義する(例えばid
がInt
、ないString
ですInt
の表現。そこから
let people = [
Person(
id: 1,
picture: "picture1.png",
firstName: "John",
lastName: "Smith"
),
Person(
id: 2,
picture: "picture2.png",
firstName: "Mike",
lastName: "Rutherford"
),
]
どのような方法で並べ替えることができます。
people.sorted{ $0.id < $1.id }
people.sorted{ $0.id > $1.id }
people.sorted{ $0.picture < $1.picture }
people.sorted{ $0.picture > $1.picture }
people.sorted{ $0.firstName < $1.firstName }
people.sorted{ $0.firstName > $1.firstName }
people.sorted{ $0.lastName < $1.lastName }
people.sorted{ $0.lastName > $1.lastName }
ありがとうございました。これは完璧でした。 –
@BenoitDesruisseauxこの回答があなたの質問を満たしていれば、それを受け入れたものとしてマークしてください – Alexander
数字の文字列比較(例:どこ特定index
の項目の "2" < "10"):
let index = 1 // sort by second entry
myArray.sort { $0[index].compare($1[index], options: .numeric) == .orderedAscending }
あなたが数値比較を必要としない場合(例えば、 "10" < "2"):
myArray.sort { $0[index] < $1[index] }
他の人が指摘しているように、あなたは実際にオブジェクトを単なる文字列として表現するのではなく、カスタムstruct
またはclass
の配列を使用するべきです。
ありがとうございました。 –
構造体またはクラスを使用してこの関連データを自己完結型インスタンスにパッケージ化すると、はるかに簡単になります。 – Alexander
文字列の配列を使うのではなく、indexのようなプロパティ(1または2の意味)、pictureName、Name、FamilyNameを持つ配列の情報を表す 'struct'または' class'を持つことをお勧めします。 – Larme
ありがとうございました。 –