convert a number from base 10 to base 16 in swift

To convert a number from base 10 to base 16 (hexadecimal), you can use the String constructor that takes an integer and a radix as arguments. Here is an example Swift function that converts a decimal number to hex:

main.swift
func decimalToHex(decimal: Int) -> String {
    let hex = String(decimal, radix: 16)
    return hex
}
102 chars
5 lines

You can call this function with a decimal number as the argument:

main.swift
let decimal = 123
let hex = decimalToHex(decimal: decimal)
print(hex) // prints "7b"
85 chars
4 lines

The String constructor returns a string representation of the number in the specified radix, which in this case is 16 for hexadecimal.

gistlibby LogSnag