Search code examples
iosswiftuibuttonibaction

Methods declared must return void (not float)


I'm attempting to return two float values, width and height using a standard UIButton function. I added the "-> Float" but I am greeted with this error. If I change it to "-> Void" then I am left with Unexpected non-void return value in void function. What am i doing wrong here?

@IBOutlet weak var buttonValue: UIButton!
@IBAction func smallB(_ sender: Any) -> Float {

    var inital = 2
    let divisble = 2

    var width: Float
    var height: Float



    if inital % divisble == 0
    {
        width = 0.14
        height = 0.07
        buttonValue.titleLabel?.text = "Big"
        inital + 1
    }
    else
    {
        width = 0.28
        height = 0.14
        buttonValue.titleLabel?.text = "Small"
        inital + 1
    }

    return width
    return height

}

Solution

  • IBAction function can be invoked/called by user interaction on any UIElements like Button, Switch, Segment Controller. And its response (return type) goes back to user interface element, you may not get float values in your code, if your use IBAction and attach that action to your Interface Builder

    Remove return type from your IBAction method, if you've connected method with your Interface Builder Button element. It would be meaningless for you to return value, if your action is generated from IBOutlet element.

    @IBAction func smallB(_ sender: Any) {
       // action contents
    
       // also remove following return statements
       // return width
       //  return height
    }
    

    But if you really want to return height & width (two float values) as response to this function call then you should call it programmatically, and change function declaration like:

    func smallBTest(_ sender: Any) -> CGSize {
       // action contents
    
      //Update your return statement like
      return CGSize(width: width, height: height)
    }
    
    let size: CGSize = smallBTest(<button instance > buttonValue)
    print("Size: Width = \(size.width)  -- Height = \(size.Height)")
    
    // or you can try this as well
    @IBAction func smallB(_ sender: Any) {
      let size: CGSize = smallBTest(sender)
       print("Size: Width = \(size.width)  -- Height = \(size.Height)")
    }