【问题标题】:How to assign default parameter value in closure with swift?如何用swift在闭包中分配默认参数值?
【发布时间】:2022-01-11 09:30:53
【问题描述】:

我有一个闭包函数,我想在其中分配一个默认值,但我收到一个错误,因为 元组类型中不允许默认参数

func getResponse(address: String, completion : @escaping ((_ lat : CLLocationDegrees, _ long : CLLocationDegrees, _ attributedPlaceName: String, _ placeId: String? = nil)->())) {
    
  }

【问题讨论】:

  • 我认为你根本做不到,因为闭包是一个带有返回值的“元组”。所以如果这在(Int, Int? = nil, Int? = nil)(1,2) 之间是可能的,是(1, nil, 2) 还是(1, 2, nil)?在该元组中命名变量并没有太大变化。
  • 只有函数定义可以有默认参数值。这是一个函数/闭包type。类型不能有默认参数值。
  • 你的方法是错误的。完成块返回值,但完成块的实现可以通过使用_ 而不是值的变量名来简单地忽略这些。

标签: swift closures


【解决方案1】:

你需要做一个老式的重载,即

有 3 个参数:

func getResponse(
    address: String,
    completion: @escaping (
        (
            _ lat: CLLocationDegrees,
            _ long: CLLocationDegrees,
            _ attributedPlaceName: String
        ) -> ()
    )
) {
    //
}

getResponse(address: "foo") { lat, long, attributedPlaceName in
    //
}

有 4 个参数:

func getResponse(
    address: String,
    completion: @escaping (
        (
            _ lat: CLLocationDegrees,
            _ long: CLLocationDegrees,
            _ attributedPlaceName: String,
            _ placeId: String?
        ) -> ()
    )
) {
    //
}

getResponse(address: "bar") { lat, long, attributedPlaceName, placeId in
    //
}

虽然我真的不知道你为什么要打扰。如果您只有 4 参数签名,则可以使用下划线随意忽略任何参数,即

getResponse(address: "bar") { lat, long, attributedPlaceName, _ in
    // 
}

【讨论】:

    【解决方案2】:

    不要使用多个参数,而是定义一个模型来保存您的数据:

    struct Place {
        let latitude: CLLocationDegrees
        let longitude: CLLocationDegrees
        let attributedName: String
        let id: String?
    
        init(
            latitude: CLLocationDegrees,
            longitude: CLLocationDegrees,
            attributedName: String,
            id: String? = nil
        ) {
            self.latitude = latitude
            self.longitude = longitude
            self.attributedName = attributedName
            self.id = id
        }
    }
    

    并使用该类型:

    func getResponse(address: String, completion: @escaping (Place) -> Void) {    
    }
    

    您的代码将更易于阅读,并且您在 Place 初始化程序中隐藏了默认参数值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多