Search code examples
swifttextuilabel

Add 2 float values in UILabel from 2 difference functions


I'm new to Swift and I'm stuck with this simple issue, hope someone can help.

I'm trying to assign float value to 2 UILabels deliveryCollectionLabel and adminFeeLabel with if logic in 2 different functions as shown below and then on third function named totalCost I'm trying to add them values but I'm getting an error:

Binary operator '+' cannot be applied to two '()' operands

first question: is below the correct way to assign a Float value to labels deliveryCollectionLabel and adminFeeLabel?

secondly: what is the correct way to add values of these 2 functions into Float which will be used to add to another float value later on in the code?

private func deliveryCharge() {
    if deliveryCollectionLabel.text! == "Delivery" {
        deliveryChargeLabel.text! = "2.50"
    } else {
        deliveryChargeLabel.text! = "0.00"
    }
}
private func adminFee () {
    adminFeeLabel.text! = "0.50"
}
private func totalCost() {
   var totalOrderCost = 0
    totalOrderCost = deliveryCharge() + adminFee()
}

Solution

  • You can use it that way.

    private func getDeliveryCharge() -> Double {
        if deliveryCollectionLabel.text! == "Delivery" {
             return 2.50
        }
      return 0.0
    }
    
    private func getAdminFee() -> Double {
        return 0.50
    }
    
    private func getTotalCost() -> Double {
      return getDeliveryCharge() + getAdminFee()
    }
    

    [USE]:

    deliveryChargeLabel.text = "\(getDeliveryCharge())"
    adminFeeLabel.text = "\(getAdminFee())"
    print("\(getTotalCost())")
    

    I hope it helps.