LoginSignup
1
3

More than 3 years have passed since last update.

配列の要素を置き換える【Swift 5】

Posted at

こんにちは、@Zhalen です。

このExtensionでは、配列の指定した要素を、同じ型の要素に置き換えるだけの面白味のないメソッドを定義します。
お手軽にお使いください。

Extension


//ReplaceMent
extension Array where Element: Equatable {
    mutating func replace(before: Array.Element, after: Array.Element) {
        self = self.map { ($0 == before) ? after : $0 }
    }
}

Usage

Ex1

var array: [Int] = [1, 2, 3, 4, 5]

array.replace(before: 1, after: 6)//1を6に置き換える

print(array)
//[6, 2, 3, 4, 5]
1
3
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
1
3