2

I just started learning swift, and I'm trying to convert feet/inches using swift. Below is the code i wrote.

func feetToInchesInt(feet:Int) -> Double
{
    return Double(feet*12)
}

func feetToInchesDouble(feet:Double) -> Double
{
    return feet*12
}

func feetToInchesFloat(feet:Float) -> Float
{
    return feet*12
}

func InchesToFeetInt(inches:Int) -> Double
{
    return Double(inches/12)
}

func InchesToFeetDouble(inches:Double) -> Double
{
    return inches/12
}

func InchesToFeetFloat(inches:Double) -> Double
{
    return inches/12
}

Now, i want to replace those functions with two generics. I tried many but can't figure out. Below is where i got stuck. Please help.

func feetToInches<T>(feet:T) -> Double
{
    return feet*12
}

func inchesToFeet<T>(inches:T) -> Double
{
    return inches/12
}

print(feetToInches(10))
adolfosrs
  • 9,286
  • 5
  • 39
  • 67
Hyungjun Chun
  • 41
  • 1
  • 4

1 Answers1

4

For your generic class why not just use a Double? It works when you give the function both an Int and a Float.

From the iOS Developer Website:

Double has a precision of at least 15 decimal digits, whereas the precision of Float can be as little as 6 decimal digits. The appropriate floating-point type to use depends on the nature and range of values you need to work with in your code. In situations where either type would be appropriate, Double is preferred.

Then your generic code would just be:

func feetToInches(feet: Double) -> Double {
    return inches * 12
}

func inchesToFeet(inches: Double) -> Double {
    return inches / 12
}
Clashsoft
  • 11,553
  • 5
  • 40
  • 79
Kitson
  • 1,153
  • 9
  • 22
  • That might be the best-suited solution here, but it is *not generic code*. Also the function do *not* take an `Int` or `Float` argument, `feetToInches(Float(1.0))` or `inchesToFeet(Int(12))` would not compile. – Martin R Sep 28 '15 at 14:32