If / else expressions

I tried applying this idea to some ternary expressions from the standard library. I prefer the if expression version in nearly every case, particularly how it lets me know right up front that I'm dealing with a conditional expression. When assignments use ?: I always have to backtrack once I hit the ? and realize that what I've read so far is only the condition, not what's being assigned.

Simple, common usage from ArrayBody.swift:

// before
_capacityAndFlags
    = newValue ? _capacityAndFlags | 1 : _capacityAndFlags & ~1
// after
_capacityAndFlags = 
    if newValue { _capacityAndFlags | 1 } 
    else { _capacityAndFlags & ~1 }

Return example from Algorithms.swift — this is the only one that potentially increases confusion, since reading it as an English sentence appears to conditionalize the return:

// before
return y < x ? y : x
// after
return if y < x { y } else { x }

From DebuggerSupport.swift:

// before
let bullet = isRoot && (count == 0 || !willExpand) ? ""
    : count == 0    ? "- "
    : maxDepth <= 0 ? "▹ " : "▿ "
// after
let bullet = 
    if isRoot && (count == 0 || !willExpand) { "" }
    else if count == 0 { "- " }
    else if maxDepth <= 0 { "▹ " }
    else { "▿ " }

Inside a function call, from DebuggerSupport.swift:

// before
print(remainder == 1 ? " child)" : " children)", to: &target)
// after
print(if remainder == 1 { " child)" } else { " children)" }, to: &target)

A bigger chunk, from ClosedRange.swift:

// before
let lower =
    limits.lowerBound > self.lowerBound ? limits.lowerBound
        : limits.upperBound < self.lowerBound ? limits.upperBound
        : self.lowerBound
let upper =
    limits.upperBound < self.upperBound ? limits.upperBound
        : limits.lowerBound > self.upperBound ? limits.lowerBound
        : self.upperBound
// after
let lower =
    if limits.lowerBound > self.lowerBound { limits.lowerBound }
    else if limits.upperBound < self.lowerBound { limits.upperBound }
    else { self.lowerBound }
let upper =
    if limits.upperBound < self.upperBound { limits.upperBound }
    else if limits.lowerBound > self.upperBound { limits.lowerBound }
    else { self.upperBound }
12 Likes