What is the `some` keyword in Swift(UI)?

后端 未结 11 643
庸人自扰
庸人自扰 2020-12-04 04:54

The new SwiftUI tutorial has the following code:

struct ContentView: View {
    var body: some View {
        Text(         


        
11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 05:38

    I'll try to answer this with very basic practical example (what is this an opaque result type about)

    Assuming you have protocol with associated type, and two structs implementing it:

    protocol ProtocolWithAssociatedType {
        associatedtype SomeType
    }
    
    struct First: ProtocolWithAssociatedType {
        typealias SomeType = Int
    }
    
    struct Second: ProtocolWithAssociatedType {
        typealias SomeType = String
    }
    

    Before Swift 5.1, below is illegal because of ProtocolWithAssociatedType can only be used as a generic constraint error:

    func create() -> ProtocolWithAssociatedType {
        return First()
    }
    

    But in Swift 5.1 this is fine (some added):

    func create() -> some ProtocolWithAssociatedType {
        return First()
    }
    

    Above is practical usage, extensively used in SwiftUI for some View.

    But there is one important limitation - returning type needs to be know at compile time, so below again won't work giving Function declares an opaque return type, but the return statements in its body do not have matching underlying types error:

    func create() -> some ProtocolWithAssociatedType {
        if (1...2).randomElement() == 1 {
            return First()
        } else {
            return Second()
        }
    }
    

提交回复
热议问题