乘法运算

 收藏

嗨,我想乘以5 * 5,但是我不想写“ *”符号,而是想将其存储在var中,但是我只是想不出怎么做

我不想做什么: var sum = 5 * 5 打印(总和)

我想做的事: var a =“ *” var sum = 5 a 5 打印(总和)

回复
  • let multiply: (Int, Int) -> Int = (*)
    let product = multiply(5, 5)
    
    var operate: (Int, Int) -> Int
    
    operate = (*)
    let product = operate(5, 5)
    
    operate = (+)
    let sum = operate(5, 5)
    

  • 在为该过程编写简单函数之后,您就可以满足您的要求,

    var a = "*" //your changing operator 
    
    func calc(type:String,val1:Int,val2:Int)->Int{
    
        //you can change values types to double if you want
    
        switch type {
        case "*": return val1*val2
        case "/": return val1/val2
        case "-": return val1-val2
        case "+": return val1+val2
        default:
            return 0
        }
    }
    
    print(calc(type: a, val1: 5, val2: 5))// result 25