Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding new line character in a String in "Swift 3"

Tags:

xcode

ios

swift3

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.

like image 319
Mohammad Aamir Avatar asked Nov 08 '25 10:11

Mohammad Aamir


1 Answers

Short answer for Swift 5+

You can use

string.contains { $0.isNewline }

or KeyPath based syntax

string.contains(where: \.isNewline)

to detect if string contains any newline character.


Long answer

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

like image 56
Lukas Kukacka Avatar answered Nov 10 '25 01:11

Lukas Kukacka