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

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

    I think what all the answers so far are missing is that some is useful primarily in something like a DSL (domain-specific language) such as SwiftUI or a library/framework, which will have users (other programmers) different from yourself.

    You would probably never use some in your normal app code, except perhaps insofar as it can wrap a generic protocol so that it can be used as a type (instead of just as a type constraint). What some does is to let the compiler keep a knowledge of what specific type something is, while putting a supertype facade in front of it.

    Thus in SwiftUI, where you are the user, all you need to know is that something is a some View, while behind the scenes all sort of hanky-panky can go on from which you are shielded. This object is in fact a very specific type, but you'll never need to hear about what it is. Yet, unlike a protocol, it is a full-fledged type, because wherever it appears it is merely a facade for some specific full-fledged type.

    In a future version of SwiftUI, where you are expecting a some View, the developers could change the underlying type of that particular object. But that won't break your code, because your code never mentioned the underlying type in the first place.

    Thus, some in effect makes a protocol more like a superclass. It is almost a real object type, though not quite (for example, a protocol's method declaration cannot return a some).

    So if you were going to use some for anything, it would most likely be if you were writing a DSL or framework/library for use by others, and you wanted to mask underlying type details. This would make your code simpler for others to use, and would allow you to change the implementation details without breaking their code.

    However, you might also use it in your own code as a way of shielding one region of your code from the implementation details buried in another region of your code.

提交回复
热议问题