Skip to content

Instantly share code, notes, and snippets.

@KentarouKanno
Last active May 6, 2018 00:45
Show Gist options
  • Save KentarouKanno/5bf50db63f8dfbd365182fc3c4d90adf to your computer and use it in GitHub Desktop.
Save KentarouKanno/5bf50db63f8dfbd365182fc3c4d90adf to your computer and use it in GitHub Desktop.

Array Contains

★ Arrayが範囲内に含まれているかを判定する
参考URL: indexがArrayの範囲内かチェックする色々な書き方

// 1. array.count(要素数)を利用する
guard index >= 0 && index < array.count else { return }

// 2. array.indices(インデックスの配列)とcontains(配列に含まれるか)を利用する
guard array.indices.contains(index) else { return }

// 3. 半区間演算子..<とarray.count(要素数)とcontains(配列に含まれるか)を利用する
guard (0..<array.count).contains(index) else { return }

// 4. array.indices(インデックスの配列)と~=(パターンマッチ)を利用する
guard array.indices ~= index else { return }

// 5. 半区間演算子..<とarray.count(要素数)と~=(パターンマッチ)を利用する
guard 0..<array.count ~= index else { return }

// 6. case文を利用する
guard case array.indices = index else { return }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment