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

后端 未结 11 642
庸人自扰
庸人自扰 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:45

    The some keyword from Swift 5.1 (swift-evolution proposal) is used in conjunction with a Protocol as a return type.

    Xcode 11 release notes present it like that:

    Functions can now hide their concrete return type by declaring what protocols it conforms to, instead of specifying the exact return type:

    func makeACollection() -> some Collection {
        return [1, 2, 3]
    }
    

    Code that calls the function can use the interface of the protocol, but doesn’t have visibility into the underlying type. (SE-0244, 40538331)

    In the example above, you don't need to tell that you're going to return an Array. That allows you to even return a generic type that just conforms to Collection.


    Note also this possible error that you may face:

    'some' return types are only available in iOS 13.0.0 or newer

    It means that you're supposed to use availability to avoid some on iOS 12 and before:

    @available(iOS 13.0, *)
    func makeACollection() -> some Collection {
        ...
    }
    

提交回复
热议问题