Count the number of lines in a Swift String

后端 未结 3 1183
天涯浪人
天涯浪人 2021-01-14 10:15

After reading a medium sized file (about 500kByte) from a web-service I have a regular Swift String (lines) originally encoded in .isolatin1. Befor

3条回答
  •  温柔的废话
    2021-01-14 10:56

    Swift 5 Extension

    extension String {
        
        func numberOfLines() -> Int {
            return self.numberOfOccurrencesOf(string: "\n") + 1
        }
        
    }
    

    Example:

    let testString = "First line\nSecond line\nThird line"
    let numberOfLines = testString.numberOfLines() // returns 3
    

提交回复
热议问题