Max Nelson Max Nelson - 1 month ago 10
iOS Question

Why can't I pass variables into my swift function?

Why doesn't this code work? I tried this in a playground with the variables I'm passing in as ints and it worked. My Code

Answer

You are missing the sideB: in your function call. I didn't want to rewrite your code (since you posted an image) but here's the working function call.

func calcButton(sender: AnyObject) {
    let a: Int = 10
    let b: Int = 11

    calculate(a, sideB: b) //<-- Missing it here
}

func calculate(sideA: Int, sideB: Int) -> Int {
    let a = sideA + sideB
    return a
}

you might also want to have both variables in the function call so you can do this instead:

func calcButton(sender: AnyObject) {
    let a: Int = 10
    let b: Int = 11

    calculate(sideA: a, sideB: b)
}

func calculate(sideA A: Int, sideB B: Int) -> Int {
    return A + B
}

Just an FYI, use tab completion instead of writing out the function. Xcode will let you know all the function variables with placeholders so you can type them in.

Comments