I was trying to make an extension for safe unwrapping, and I was working in 2 version of it, one long code form, second short code! But unexpectedly they do not work! So far as I can see to my code, I just made all things correct! What I am missing to fix both version?
struct ContentView: View {
let test: String? = "Hello, World!"
var body: some View {
Text(test.safeUnwrapV1(defaultValue: "Empty!"))
Text(test.safeUnwrapV2(defaultValue: "Empty!"))
}
}
extension Optional {
func safeUnwrapV1<T>(defaultValue: T) -> T {
let wrappedValue: T? = (self as? T?) ?? nil
if let unwrappedValue: T = wrappedValue { return unwrappedValue }
else { return defaultValue }
}
func safeUnwrapV2<T>(defaultValue: T) -> T {
return (self as? T) ?? defaultValue
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…