Home > Enterprise >  SWIFT unordered function parameters
SWIFT unordered function parameters

Time:05-31

(SWIFT SPECIFICALLY) lets say i have a function like this

static func * (complex: i, number: Int) -> i{
    return i(number*complex.times)
}

as you can see, i want to be able to multiply a complex number by an integer. however, this only works if the complexe number is on the left side (such as: i(5) * 5) so i can do i(10) * 8 but not 8 * i(10) because the function parameters have to be in a certain order. I am aware i can just make a second overloaded function, but is tehre any way around it? im learning swift and it would be nice to learn some tips and tricks. THanks, from me

CodePudding user response:

No there isn't, but you can write one function to call the other to avoid duplicating the implementation.

static func * (complex: i, number: Int) -> i{
    return i(number*complex.times)
}

static func * (number: Int, complex: i) -> i{
    return complex * number
}

CodePudding user response:

No, the parameters to Swift functions have a specific order. Swift does not support unordered parameters. As Craig points out in his answer, you can provide multiple versions of a function that take their parameters in different orders and have them all call the same function that actually implements the code.

  • Related