Help us understand the problem. What is going on with this article?

Arrayを複数回す際に役立ちそうなこと

More than 3 years have passed since last update.

2つのArrayを回して値を取り出したい
アプリの履歴管理とかはstructでまとめてArrayにするのが定石だけど
例えばファイルをリネームするときにわざわざstructを作りたくないのでタプルで回す

普通にやると

let items = try! FileManager.default.contentsOfDirectory(atPath: path)
let renamedItems = items.map{$0.replace("aaa",with:"bbb")}
let tuples = [(String,String)]
for i in items.count-1 {
   tuples.append(items[i], renamedItems[i])
}
tuples.forEach{
   ...
}

となり少し冗長、できればループはメソッドチェーンでやりたい。

タプルで回す

Arrayにextensionで実装

extension Array{
    func tupled<T>(_ items:[T])->[(Element,T?)]{return self.enumerated().map{($1,items.index(at: $0))}}
    func index(at index:Int)->Element?{return index >= 0 && index < self.count ? self[index] : nil}
}


let items = try! FileManager.default.contentsOfDirectory(atPath: path)
let renamedItems = items.map{$0.replace("aaa",with:"bbb")}
items.tupled(renamedItems).forEach{atPath,toPath in
    guard let toPath = toPath else {return}
    try! FileManager.default.moveItem(atPath: atPath, toPath: toPath)
}

満足...  (スナネコ) CzdtZdRUoAAc1LT.jpg

ObuchiYuki
未踏2020/アプリ甲子園優勝/U22プロコン経済産業省商務局長賞/セキュキャンアワード /seccamp19/香港→開成→mast19
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした