
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if String Contains Special Characters in Swift
To check if a string contains a special character in swift we can use conditionals like if else or switch but that would need a lot of conditions to be executed, making programming as well as execution time consuming. So in this example we’ll see how to do the same task with regular expressions and another method that swift provides to check if some character exists in a character set.
Method 1 − Using regular expression
Let’s create an extension of String and add the following code into that
extension String { var containsSpecialCharacter: Bool { let regex = ".*[^A-Za-z0-9].*" let testString = NSPredicate(format:"SELF MATCHES %@", regex) return testString.evaluate(with: self) } }
We can run the following code as an example shown below.
override func viewDidLoad() { super.viewDidLoad() print("3r42323".containsSpecialCharacter) print("!--%332".containsSpecialCharacter) }
Output
Here is the result for method 1
Now we’ll see the same example with method 2.
Method 2
let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" ) if "3r42323".rangeOfCharacter(from: characterset.inverted) != nil { print("true") } else { print("false") } if "!--%332".rangeOfCharacter(from: characterset.inverted) != nil { print("true") } else { print("false") }
Output
The result produced is shown below.
Advertisements