Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

swiftui - Issue about extending Optional with Generic Type in Swift

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There's no need to define your own generic type parameter. Optional is already generic and its generic type parameter is called Wrapped. So you simply need to declare the type of the default value to be Wrapped.

extension Optional {
    func defaultValue(_ value: Wrapped) -> Wrapped {
        self ?? value
    }
}

struct ContentView: View {

    let test: String? = "Hello, World!"

    var body: some View {
        Text(test.defaultValue("Empty!"))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...