1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】配列(Array)操作について

Posted at

配列とは

Swiftにおいて、配列は非常に重要なデータ構造のひとつです。配列には複数の要素を格納することができ、それぞれの要素にはインデックスを用いてアクセスすることができます。Swiftには、配列に対して様々な操作を行うための機能が用意されています。

例文

配列の宣言と初期化

// 空の配列
var emptyArray: [Int] = []

// 要素を指定して初期化
var arrayWithValues: [Int] = [1, 2, 3]

// 省略形
var shorthandArray: [Int] = [1, 2, 3]

// 要素数を指定して初期化
var arrayWithCount = Array(repeating: 0, count: 3)

配列の要素の追加と削除

var fruits = ["apple", "banana", "orange"]

// 要素の追加
fruits.append("grape") // ["apple", "banana", "orange", "grape"]
fruits.insert("melon", at: 2) // ["apple", "banana", "melon", "orange", "grape"]

// 要素の削除
fruits.remove(at: 1) // "banana", ["apple", "melon", "orange", "grape"]
fruits.removeLast() // "grape", ["apple", "melon", "orange"]
fruits.removeAll() // []

配列の要素の取得と置換

var numbers = [1, 2, 3, 4, 5]

// 要素の取得
let firstNumber = numbers[0] // 1
let lastNumber = numbers[numbers.count - 1] // 5
let sliceNumbers = numbers[1...3] // [2, 3, 4]

// 要素の置換
numbers[2] = 6 // [1, 2, 6, 4, 5]

配列の並び替えと検索

var numbers = [5, 2, 4, 1, 3]

// ソート
numbers.sort() // [1, 2, 3, 4, 5]
numbers.sort(by: >) // [5, 4, 3, 2, 1]

// 検索
let index = numbers.firstIndex(of: 3) // 2
let filteredNumbers = numbers.filter { $0 > 3 } // [5, 4]
  </div>

最後に

iOSアプリ開発をしています。
主にSwiftですが、最近は熱が入ってきてFlutterも🦾
色々やってます。もし良かったら見てってください。

1
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?