Generic operators

You want to make the exponentiation operator work for all kind of integer types. Update your operator implementations as follows:

func **<T: Integer>(lhs: T, rhs: Int) -> T { var result = lhs

for _ in 2...rhs { result *= lhs

}

return result

}

func =<T: Integer>(lhs: inout T, rhs: Int) { lhs = lhs rhs

}

Notice the Integer type constraint on the generic parameter. This constraint is required here as the *= operator used in the function body isn't available on any type T, but it is available on all types that conform to the Integer protocol. The function’s body is the same as before, since the generic operator does the same thing as its non-generic equivalent.

Your previous code should still work. Now that the operator is generic, test it with some types other than Int:

let unsignedBase: UInt = 2

let unsignedResult = unsignedBase ** exponent

let base8: Int8 = 2

let result8 = base8 ** exponent

let unsignedBase8: UInt8 = 2

let unsignedResult8 = unsignedBase8 ** exponent

let base16: Int16 = 2

let result16 = base16 ** exponent

let unsignedBase16: UInt16 = 2

let unsignedResult16 = unsignedBase16 ** exponent

let base32: Int32 = 2

let result32 = base32 ** exponent

let unsignedBase32: UInt32 = 2

let unsignedResult32 = unsignedBase32 ** exponent

let base64: Int64 = 2

let result64 = base64 ** exponent

let unsignedBase64: UInt64 = 2

let unsignedResult64 = unsignedBase64 ** exponent

The exponentiation operator now works for all integer types: Int, UInt, Int8, UInt8, Int16, UInt16, Int32, UInt32, Int64 and UInt64.

Note: You can also use the pow(::) function from the Foundation framework for exponentiation, but it doesn't work for all the above types.

results matching ""

    No results matching ""