Warpzit Warpzit - 6 months ago 24
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 {
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?


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

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


Is there a better approach than above?


Solution is just a ? away:

if lastProfile == nil || lastProfile?.id == profile.id {
    lastProfile = profile

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