Reputation: 126
I have to check if a text field string has in it some [String] from the array, but I can only check if the text field is the same of the [String].
var array = ["word1", "word2", "word3"]
if //textField.text contains some of the words in the array
{ //do something }
I start studying swift recently, please help me.
Upvotes: 1
Views: 52
Reputation: 31645
For such a case, what I suggest is to use contains(where:) method:
var array = ["word1", "word2", "word3"]
let isWordExist = array.contains("word1") // that should be true
if array.contains(textField.text!) {
// array DOES contains the textfield's text
} else {
// array DOES NOT contains the textfield's text
}
Also
if you are interested in counting the given string in an array, I would suggest to use the filter method, as follows:
var array = ["word1", "word1", "Word1", "Word1", "word2", "Word2"]
let numberOfMyWord = array.filter { $0 == "word1" }.count // that should be 2
let numberOfTextFieldText = array.filter { $0 == textField.text! }.count
Hope this helped.
Upvotes: 0
Reputation: 4795
It's pretty simple. First make sure to add this before your class ViewController: UIViewController{}
:
import Foundation
And then, you can find the number of common words like so:
var array = ["word1", "word2", "word3 and word 4"]
var count=0
var s=textField.text!
for item in array{
if s.components(separatedBy: " ").contains(item){
count+=1
}
}
if count > 0{ // do something here
print("There are \(count) in the text field from the array")
}
And if the array contains elements with spaces, do something like this:
var array = ["word1", "word2", "word3"]
var count=0
var s=textField.text!
for item in array{
if s.contains(item){
count+=1
}
}
if count > 0{ // do something here
print("There are \(count) in the text field from the array")
}
If a word is found, the variable count
increases by 1. After that, you check if the count
is higher than 0, and if so, you do what you want there.
The final code will look like this:
import Foundation
import UIKit
class myClass: UIViewController{
@IBOutlet weak var textField: UITextField!
var array = ["word1", "word2", "word3"]
var count=0
@IBAction func buttonPressed(_ sender: UIButton){
var s=textField.text!
for item in array{
if s.components(separatedBy: " ").contains(item){
count+=1
}
}
if count > 0{
print("There are \(count) in the text field from the array")
}
}
}
Hope it helps!
Upvotes: 2