Why does the following always print "prefix" which is incorrect but print "no prefix" when String is not optional or implicitly unwrapped optional?
var value:String! = "aaa" // Same incorrect behavior on Optional String as well.
if value?.hasPrefix("bbb") {
NSLog("prefix")
}
else {
NSLog("no prefix")
}
The if statement is checking if the statement returns a value or nil, not if it returns true or false. You can use another if statement to check the value of hasPrefix().
var value:String! = "aaa" // Same incorrect behavior on Optional String as well.
if let hasPrefix = value?.hasPrefix("bbb") {
if hasPrefix{
NSLog("prefix")
}
else {
NSLog("no prefix")
}
}
else {
NSLog("nil value")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With