はじめに
Swiftで大文字小文字を区別しない検索機能を作る方法を紹介します。
作るもの
文字列の配列から、検索キーワードを含む文字列を抽出するプログラムを作ります。
やり方
#1
一つ目は、StringProtocol
のlocalizedCaseInsensitiveContains
メソッドを使う方法です。
このメソッドは大文字小文字を区別せずに、引数の文字列を含むかどうか判定します。
import Foundation
func search(_ keyword: String, in strings: [String]) -> [String] {
strings.filter { $0.localizedCaseInsensitiveContains(keyword) }
}
let strings = ["Apple", "Banana", "Orange", "Grape", "Peach", "Pineapple"]
let keyword = "apple"
let result = search(keyword, in: strings)
print(result) // ["Apple", "Pineapple"]
#2
二つ目は、StringProtocol
のrange(of:options:)
メソッドを使う方法です。
このメソッドは、引数の文字列を含む場合はその範囲を、含まない場合はnil
を返します。
optionsに.caseInsensitive
を指定することで、大文字小文字の区別をなくせます。
import Foundation
func search(_ keyword: String, in strings: [String]) -> [String] {
strings.filter { $0.range(of: keyword, options: .caseInsensitive) != nil }
}
let strings = ["Apple", "Banana", "Orange", "Grape", "Peach", "Pineapple"]
let keyword = "apple"
let result = search(keyword, in: strings)
print(result) // ["Apple", "Pineapple"]
#3
三つ目は、lowercased
を使って検索される文字列と検索キーワードを小文字に変換してから判定する方法です。
import Foundation
func search(_ keyword: String, in strings: [String]) -> [String] {
strings.filter { $0.lowercased().contains(keyword.lowercased()) }
}
let strings = ["Apple", "Banana", "Orange", "Grape", "Peach", "Pineapple"]
let keyword = "apple"
let result = search(keyword, in: strings)
print(result) // ["Apple", "Pineapple"]
まとめ
1番目の方法が一番簡単ですね。検索機能のあるアプリを作るときはぜひ試してみてください。この記事が参考になったという方は、いいねとフォローよろしくお願いします。
参考リンク