How can I check to see if a string contains characters of whitespace/alphanumeric/etc?

后端 未结 5 781
执念已碎
执念已碎 2021-02-04 02:19

How can you use the \"ctype.h\" library in Swift to be able to use isAlpha or isSpace on characters? Or is there a better, Swift, way of doing it?

5条回答
  •  感情败类
    2021-02-04 03:08

    Shorter extension (swift 4.1)

    extension String {
        var containsWhitespace : Bool {
            return(self.rangeOfCharacter(from: .whitespacesAndNewlines) != nil)
        }
    }
    

    You can change the .whitespacesAndNewlines with any other CharacterSet like this:

    extension String {
        var containsDigits : Bool {
            return(self.rangeOfCharacter(from: CharacterSet.decimalDigits) != nil)
        }
    }
    

提交回复
热议问题