3

How can I check if a String (for example "apple") contains text that I typed in a UITextField (for example "p" or "pp").
If the String contains the UITextField's text, I want to print a message - for example: "apple contains pp".

Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41
NoNameL
  • 41
  • 1
  • 6
  • 1
    Try this http://stackoverflow.com/questions/24034043/how-do-i-check-if-a-string-contains-another-string-in-swift – Pet Rat Jun 19 '16 at 13:42

2 Answers2

3

You can achieve that like so

class youClass: NSObject {
  var yourTextFieldName = UITextField()

   func someMethod() {
     var apple = "apple"
     if apple.containsString(self.yourTextfieldName.text!) {
        print("apple contains \(self.yourTextfieldName.text!)")
     }
   }
}
Akshansh Thakur
  • 5,163
  • 2
  • 21
  • 38
0

You could extend String:

extension String {
  @discardableResult
  func containsText(of textField: UITextField) -> Bool {
    // Precondition
    guard let text = textField.text else { return false }

    let isContained = self.contains(text)
    if isContained { print("\(self) contains \(text)") }
    return isContained
  }
}

Instead of just printing a result, it also returns a Bool indicating whether or not the textField's text was contained in the String. The @discardableResult attribute allows you to ignore the return value if you want to though, without generating a compiler warning.

You could also take a reversed approach, by extending UITextField:

extension UITextField {
  @discardableResult
  func textIsContained(in target: String) -> Bool {
    // Precondition
    guard let text = self.text else { return false }

    let isContained = target.contains(text)
    if isContained { print("\(target) contains \(text)") }
    return isContained
  }
}

You would use these methods as follows:

// Your `UITextField`
let textField = UITextField()
textField.text = "pp"

// String extension:
"apple".containsText(of: textField) // returns `true` and prints "apple contains pp"

// UITextField extension:
textField.textIsContained(in: "apple") // returns `true` and prints "apple contains pp"
Marcus Rossel
  • 3,196
  • 1
  • 26
  • 41