How to use for forced unwrap in Swift 5.0 / Xcode

Unfortunately you can't use the character as a postfix operator like !, but here's an alternative:

postfix operator ⏰
extension Optional {
    postfix public static func ⏰(a: Optional<Wrapped>) -> Wrapped {
        return a!
    }
}

Example:

var crashme : String? // nil
print(crashme⏰) // crash

I like this alternative symbol since it implies a ticking time bomb, which is just what an IUO is. Or maybe it implies Hey wake up!


As discussed in the comments & Matt's answer, the character is not available to be an operator, so if you specifically want to use it, then you can do it with an extension as seen here.

extension Optional {
    var : Wrapped {
        return self!
    }
}

var string: String? = "42"
print(string.) // 42

var number: Int? = nil
print(number.) // Fatal error: Unexpectedly found nil while unwrapping an Optional value

This extension makes use of the Optional type, so it can be used with any data type that conforms to Optional.

However, if you want to the postfix route, then the following offers an option:

postfix operator ☠
extension Optional {
    postfix static func ☠(optional: Optional<Wrapped>) -> Wrapped {
        return optional!
    }
}

var bad: String?
print(bad☠)

Sadly, the skull & crossbones do not show as well here as they do in Xcode.

enter image description here

On a serious note for OP, if you wish to enforce usage of this within a team, I would recommend a tool such as swiftlint, where you can modify the rules around force unwrapping to require some .

Tags:

Ios

Xcode

Swift