Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 🧨 for forced unwrap in Swift 5.0 / Xcode

Tags:

xcode

ios

swift

I want to be able to use 🧨 instead of ! for forced unwraps in Swift code. If this was C++ I might try using #define or something like that, but I am not sure how this could be accomplished.

I can't just globally replace ! with 🧨, as it's used for not, and for declaring force unwrap variables, and maybe some other stuff

Would it be easier with some sort of Xcode macro, or a plugin?

like image 458
Tom Schulz Avatar asked Jul 06 '19 00:07

Tom Schulz


2 Answers

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!

like image 178
matt Avatar answered Sep 23 '22 06:09

matt


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 🧨.

like image 22
CodeBender Avatar answered Sep 21 '22 06:09

CodeBender