LoginSignup
4
2

Listの行を並べ替える。

Posted at

簡単に。

.onMove(perform:) modifierを使用する。


詳細に。

このmodifierはDynamicViewContent(データから動的に生成するViewのprotocol)に定義されており、より詳細に見ると次のとおり。

func onMove(perform action: Optional<(IndexSet, Int) -> Void>) -> ...
  • onMove(...)は引数として、nilあるいはクロージャ(IndexSet, Int) -> Voidを受け取る。
    • nilを渡すことで並替機能を無効化できる。
    • クロージャの引数
      • IndexSetは、動かしたい要素(単/複数)のインデックスの集合。
      • Intは動かしたい要素が挿入されるべきインデックス。

上記クロージャに渡されることが多い下記メソッドについて。

MutableCollection.move(fromOffsets source: IndexSet, toOffset destination: Int)

sourceに渡されていない(即ち動かす対象でない要素の)インデックスに関して、
destinationよりも小さいインデックスに紐づいていた要素はcollectionの前方に、
大きいインデックスに紐づいていた要素はcollectionの後方に移動される。

var letters = Array("ABcDefgHIJKlmNO")
let lowercaseOffsets = IndexSet(...) // 小文字たちのoffsets
letters.move(fromOffsets: lowercaseOffsets, toOffset: 2)
// String(letters) == "ABcefglmDHIJKNO"
    
// Reset the `letters` array.
letters = Array("ABcDefgHIJKlmNO")
letters.move(fromOffsets: lowercaseOffsets, toOffset: 15)
// String(letters) == "ABDHIJKNOcefglm"
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2