Home > Blockchain >  How the function inverted of characterSet works in Swift(5.0)
How the function inverted of characterSet works in Swift(5.0)

Time:06-13

I have example:

let stringToCheck: String = "42"
let numbers: CharacterSet = CharacterSet.decimalDigits
let stringIsANumber: Bool = stringToCheck.rangeOfCharacter(from: numbers.inverted) == nil 

and i have two question

  1. How the function inverted works? what does it do?
  2. what range does rangeOfCharacter return?

CodePudding user response:

inverted means the opposite. For example, if you have only characters a and b and c and a character set consisting of a, its inversion is b and c. So your decimalDigits characters set, inverted, means everything that is not a decimal digit.

A range is a contiguous stretch of something, specified numerically. For example, if you have the string "abc", the range of "bc" is "the second and third characters". The range of something that isn't there at all can be expressed as nil.

So the code you have shown looks for a character that is not a digit in the original string, and if it fails to find one (so that the range is nil), it says that the string is entirely a number.

  • Related