iOS同学都清楚NSString方法可以将一个NSString对象转换成bool值,比如我们可以将服务端返回过来的“ture”or"false"转换成‘YES’or'NO',那么除了常见的对于“ture”or"false"的转换,对其他字符的转换会有什么结果呢,根据apple的文档中的这段描述:
The Boolean value of the string.
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.
根据上面apple的描述我们可以了解到3点:
- 1、如果一个字符串以"Y", "y", "T", "t"或者‘1-9’开头,那么boolValue会忽略后面的字符,直接将该字符串转换成true;
- 2、如果该字符串不是一个十进制表示(比如“0123”,‘123’返回YES,'xxx'返回NO),那么会boolValue返回NO;
- 3、如果该字符串是十进制的表示,但是前面可能前面多了一个空格,或者0后面添加了-+(比如‘ 012’,‘0+’,‘0-’),这些多余的空格和和“-、+”都会被忽略;
- (void)testStringBoolValue {
NSArray *tests = @[ @"Y",
@"N",
@"T",
@"F",
@"t",
@"f",
@"1",
@"0",
@"Yes",
@"No",
@"No really no",
@"true",
@"false",
@"To be or not to be",
@"False",
@"3567",
@"012",
@" 0123456789",
@" 0123456789",
@" 123456789",
@" 0",
@"0-",
@"+1",
@"-1",
@"xxx"
];
NSArray *boolToString = @[@"NO", @"YES"];
for (NSString *test in tests){
NSLog(@"boolValue:\"%@\" => %@", test, boolToString[[test boolValue]]);
}
}
截图.png
综上我们可以清楚的了解到,一个字符中如果以"Y", "y", "T", "t"或者‘1-9’开头,那么会返回YES,如果一个十进制的描述文本,比如“ 0123‘,’0+‘,’0-‘(’ 0123‘,前面有个空格),会忽略空格和”+“,”-“.
网友评论