1
1

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】contains(_:)で任意の文字が含まれているか調べる

Last updated at Posted at 2022-05-11

はじめに

contains(_:)メソッドを使う機会があったので備忘録として残します。

環境

  • Swift: version 5.6
  • Xcode: Version 13.3.1 (13E500a)
  • macOS: 12.3.1 (21E258)

contains(_:)メソッド

func contains(_ element: Self.Element) -> Bool
  • Sequenceプロトコルで提供されるメソッド。
  • 引数と同じ要素が含まれるかどうかを調べることができる。

使い方

例題

配列["MacBook", "iMac", "Mac Pro", "iPhone", "iPad", "Apple Watch"]に対して下記の操作行う。

  1. iPhoneが含まれているか調べる。
  2. iが含まれている製品を抽出する。

実装

let product = ["MacBook", "iMac", "Mac Pro", "iPhone", "iPad", "Apple Watch"]

//iPhoneが含まれているかを調べる。
print(product.contains("iPhone"))
//true

//filterメソッドと組み合わせて、iが含まれる製品を抽出する
let filtered = product.filter { $0.contains("i") }
print(filtered)
//["iMac", "iPhone", "iPad"]

contains(where:)メソッド

引数にクロージャを渡すcontains(where:)もあります。

func contains(where predicate: (Self.Element) throws -> Bool) rethrows -> Bool
  • 引数に渡したクロージャを満たす要素が含まれているかどうかを調べることができる。`

contains(where:)の使用例はこちら

さいごに

contains(_:)メソッドの使い方をまとめてみました。
最後まで見ていただきありがとうございました。

参考記事・書籍

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?