This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
infix operator ???: NilCoalescingPrecedence | |
extension Optional where Wrapped: Emptyable { | |
static func ???(left: Wrapped?, right: Wrapped) -> Wrapped { | |
return left.orWhenNilOrEmpty(right) | |
} | |
} | |
let optionalString: String? = nil | |
let mandatoryString = optionalString ??? "Default Value" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct MyStruct: Emptyable, CustomStringConvertible { | |
var name: String | |
var isEmpty: Bool { return name.isEmpty } | |
var description: String { return name } | |
init(name: String) { | |
self.name = name | |
} | |
} | |
var myOptional: MyStruct? = nil |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
protocol Emptyable { | |
var isEmpty: Bool { get } | |
} | |
extension Optional where Wrapped: Emptyable { | |
func orWhenNilOrEmpty(_ defaultValue: Wrapped) -> Wrapped { | |
switch(self) { | |
case .none: | |
return defaultValue | |
case .some(let value) where value.isEmpty: |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension Optional where Wrapped == String { | |
func orWhenNilOrEmpty(_ defaultValue: String) -> String { | |
switch(self) { | |
case .none: | |
return defaultValue | |
case .some(let value) where value.isEmpty: | |
return defaultValue | |
case .some(let value): | |
return value | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
cell.myLabel.text = myModel.someString |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if let text = myModel.someString, !text.isEmpty { | |
cell.myLabel.text = text | |
} else { | |
cell.myLabel.text = "Text is empty" | |
} |