Warpzit Warpzit - 3 months ago 6
Swift Question

Swift optionals nil check

So I fail to figure a 1 liner for following syntax in Swift and it is driving me nuts:

if lastProfile == nil || lastProfile.id == profile.id {
useProfile(profile)
lastProfile = profile
}


Now see I could chain it but I'd still end up with 2-3 ifs. I could pack it out but then I again end up with 2-3 ifs... Is it possible to do this in just 1 swoop?

Edit:

My colleague found an alternative (although we agree ugly):

if !(latestProfile != nil && latestProfile!.voiceId != profile.voiceId) {

}


Is there a better approach than above?

Answer

Solution is just a ? away:

if lastProfile == nil || lastProfile?.id == profile.id {
    print("true")
    lastProfile = profile
}

This prints "true" when lastProfile is nil or when lastProfile and profile have the same id. Otherwise it prints nothing.