Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hasPrefix misbehave on Optional String

Tags:

swift

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")
}
like image 837
Boon Avatar asked Jun 18 '26 12:06

Boon


1 Answers

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")
}
like image 96
Connor Avatar answered Jun 21 '26 05:06

Connor