gpt4 book ai didi

swift - 调用以函数作为参数的对象的函数

转载 作者:行者123 更新时间:2023-11-30 10:01:57 26 4
gpt4 key购买 nike

假设我有以下代码:

import Foundation

enum Operation {
case BinaryOperation ((Double, Double) -> Double)
}

var multiply = Operation.BinaryOperation({$0 * $1})

//Error: Cannot call value of non-function type 'Operation'
multiply(3.0,2.0)

我如何在这里调用函数乘法?

最佳答案

您的函数是枚举值的关联值,因此您必须在调用它之前先提取它。一种方法是使用模式匹配:

if case let .BinaryOperation(function) = multiply {
function(3.0, 2.0)
}

这也可以写成:

if case .BinaryOperation(let function) = multiply {
function(3.0, 2.0)
}

关于swift - 调用以函数作为参数的对象的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38028667/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com