Reputation: 7050
I am programming in Objective-C for iOS. I would like to parse an object of type NSString into a scalar of type BOOL.
I have a value, and I know that it will either be @"YES" or @"NO", but that YES (or) NO value is NSString and I just want to change NSString into BOOL.
How can I do that?
Please answer me if you know.
Thanks for reading.
Upvotes: 55
Views: 43074
Reputation: 1727
This property should also return true if string is 'true' that's why i think extension is needed...
extension NSString{
var boolValueExtended: Bool {
get{
return boolValue ||
self.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()).uppercaseString == "TRUE"
}
}
}
Upvotes: 0
Reputation: 1389
This would probably best be solved with a conditional, for example:
if ([myString isEqualToString:@"YES"])
myBool = YES;
else if ([myString isEqualToString:@"NO"])
myBool = NO;
Hope this helped you, good luck with your programming.
Upvotes: 0
Reputation: 100622
You should probably use NSString
's -boolValue
. To quote the documentation directly:
[Returns t]he Boolean value of the receiver’s text. Returns YES on encountering one of "Y", "y", "T", "t", or a digit 1-9—the method ignores any trailing characters. Returns NO if the receiver doesn’t begin with a valid decimal text representation of a number.
That would seem to match your input cases.
Upvotes: 22