You can't directly check if a value is Optional, but you can do it via an intermediate protocol. I use this approach:
protocol _Optional {
var value: Any? { get }
}
extension Optional: _Optional {
var value: Any? {
return self
}
}
let anyValue: Any = ... // might be an optional
if let optionalValue = anyValue as? _Optional {
// it's an optional
if let value = optionalValue.value {
// it's non-nil
print(value)
} else {
print("nil")
}
} else {
print(anyValue)
}
Weird. I can't immediately see any reason why what you've written wouldn't work in release mode.
I'd suggest if self is String instead of if "\(Wrapped.self)" == "String" though, as the latter seems a bit fragile (e.g. if the value was an NSString that test would fail).
You might also want to consider using guard let or some other more traditional way of unwrapping the self value inside orNil to avoid all those force unwraps.
Ah yes. Very good suggestions. Much more sane and readable code with those changes.
It is really weird with this difference between release and debug builds. It is easily reproducable with a Xcode project with almost only the above code.