There are several threads on how to replicate NSString's boolValue method, but most are guesses or simplifications.
Apple only gives us this brief descriptions:
This property is YES on encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. This property is NO if the receiver doesn’t begin with a valid decimal text representation of a number. The property assumes a decimal representation and skips whitespace at the beginning of the string. It also skips initial whitespace characters, or optional -/+ sign followed by zeroes.
So what does it consider as whitespace? What does "assumes a decimal representation" mean?
I am converting an existing Objective-C app and converting it to Swift, and would like a true Swift boolValue method without having to first convert the string to an NSString (ie (string as NSString).boolValue())
UPDATE: As Duncan pointed out in comments, whitespace includes much more than ASCII white space, and the original code and test harness has been updated to reflect that.
It actually turns out that the Apple terse description is complete and correct! Whitespace is the CharacterSet.whitespaces plus NULL. Runs of "0"s can be optionally prefixed by a "+" or "-".
This Swift code exactly duplicates the NSString function (at least for ASCII characters other than the Unicode whitespace):
The reason I can claim compatibility is that I created a test harness to compare the above code to the NSString
boolValuemethod, and insured that both returned the same value for 1,000,000,000 "fuzz" tests, using this code:Note that the strings contain random characters in the range from ASCII 0 to 127 and the Unicode white spaces extracted from CharacterSet.whitespaces.
Of course my coded failed several times before I got it right!
--- Based on Martin's comment, there is a NSString open source project that has a
boolValue- but it doesn't match the iOS version. However a slight modification will let it match (changes commented):