Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 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 Reply

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!"))
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...