In my app I am receiving some incoming data from a web service. In that data some wrong values can also be received like new line characters. I want to find in response string that if it contains a new line character or not.
Before Swift 3 I was able to do it like this
string.rangeOfString("\n")) == nil)
But in Swift 3 this methods is no longer available. However substring method is available which does with the help of Range.
I want to detect if my string contains "\n" how this would be accomplished using this method in Swift 3.
You can use
string.contains { $0.isNewline }
or KeyPath based syntax
string.contains(where: \.isNewline)
to detect if string contains any newline character.
Swift 5 introduced couple of new properties on Character. Those simplify such tests and are more robust then simple check for \n.
Now you can use
myCharacter.isNewline
For complete list check Inspecting a Character section in Character docs
Example:
Character("\n").isNewline // true
Character("\r").isNewline // true
Character("a").isNewline // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With