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

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

    A simple use case that springs to mind is writing generic functions for numeric types.

    /// Adds one to any decimal type
    func addOne(_ x: Value) -> some FloatingPoint {
        x + 1
    }
    
    // Variables will be assigned 'some FloatingPoint' type
    let double = addOne(Double.pi) // 4.141592653589793
    let float = addOne(Float.pi) // 4.141593
    
    // Still get all of the required attributes/functions by the FloatingPoint protocol
    double.squareRoot() // 2.035090330572526
    float.squareRoot() // 2.03509
    
    // Be careful, however, not to combine 2 'some FloatingPoint' variables
    double + double // OK 
    //double + float // error
    

提交回复
热议问题