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?
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.
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 🧨.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With