在同一函数内的其他计算中使用函数 returns

Using function returns in other calculations within same function

我已经在 ObservableObject class 的函数中计算了一个值,现在我想在 class.[=12= 的另一个计算中使用值 returned ]

代码如下,注意事项:-

  1. hole1index 是从 Core Data 中抓取的一项数据。
  2. 第一个函数 (p1h1shots) 完美运行并且 returns 是正确的值。
  3. 第二个函数 (p1h1net) 需要使用 p1h1shots 的输出来计算 return 值。
  4. 我已尝试以多种方式构建第二个函数,但不断收到类似“无法将类型 '(Int16) -> Int16' 的值转换为预期参数类型 'Int16' 显示的代码在 p1h1net 的 return 行上有此错误消息。

我是 Swiftui 的新手,所以可能会遗漏一些基本的东西,如有任何指点或线索,我们将不胜感激。如果任何其他信息有帮助,请告诉我。

提前致谢

import SwiftUI
import CoreData

class ScoreManager : ObservableObject {
 
    @Published var player1 = ""
    @Published var player2 = ""
    @Published var p1handicap = 0
    @Published var p2handicap = 0
    @Published var p1hole1gross = 0
    @Published var p1hole2gross = 0
    
    func p1h1shots(hole1index: Int16) -> Int16 {
        
        let hand = Int16(p1handicap)
        let shot = hand - hole1index
  
        if shot < 0 {
            return Int16(0)
        }
        
        if shot < 0 {
            return Int16(0)
        }
        
        if shot >= 0 && shot < 18 {
            return Int16(1)
        }
        
        if shot >= 18 && shot < 36 {
            return Int16(2)
        }
        
        if shot >= 36 && shot < 54 {
            return Int16(3)
        }
        return Int16(0)
    }

func p1h1net() -> Int16 {
        
        let gross = Int16(p1hole1gross)
        let shot = p1h1shots
        
        return Int16(gross - shot)
        
    }
}

首先,第二个 if shot < 0 表达式是多余的。

如果没有括号,您将把 函数 分配给 shot,而您必须使用参数

调用它
let shot = p1h1shots(hole1index: someInt16)

p1h1shots可以用switch

写得更高效
func p1h1shots(hole1index: Int16) -> Int16 {

    let hand = Int16(p1handicap)
    let shot = hand - hole1index
    
    switch shot {
        case 0..<18: return 1 // the literal is returned as Int16
        case 18..<36: return 2
        case 36..<54: return 3
        default: return 0
    }
}

或更短

func p1h1shots(hole1index: Int16) -> Int16 {

    let hand = Int16(p1handicap)
    let shot = hand - hole1index
    
    return 0..<54 ~= shot ? shot / 18 + 1 : 0
}