0

What is the Swift equivalent of Haskell Show to print values inside Enumerations with cases? I have read Show is pretty similar to the Java toString() method and that the Swift CustomStringConvertible maybe a good option.

For example, using print on a Fraction instance would display:

> Fraction(numerator: 1, denominator: 2)

Rather than printing the entire case, I would like to print only the numbers with a slash in between. For example "1/2".

My current code is the following:

enum MyNum: Equatable {
  case Fraction(numerator: Int, denominator: Int)
  case Mixed(whole: Int, numerator: Int, denominator: Int)
}

extension MyNum: CustomStringConvertible {
  var description: String {
    return "(\(Fraction.numerator) / \(Fraction.denominator))"
  }
}

var testFraction= MyNum.Fraction(numerator: 1, denominator: 2)
print(testFraction)
stcol
  • 131
  • 1
  • 11
  • I don’t know Haskell but in swift the equivalent to toString in java is to conform to the CustomStringConvertible protocol. But you need to improve your question and include your swift code and explain what you want to achieve and what the problem is to do so. Swift 3, really? It’s ancient by now. – Joakim Danielson Mar 07 '21 at 10:20

1 Answers1

1

You need to use a switch statement in description as well and read the associated values

extension MyNum: CustomStringConvertible {
var description: String {
  switch self {
    case .Fraction(let n, let d):
    return "\(n) / \(d)"
    case .Mixed(let w, let n, let d):
    return "\(w) \(n) / \(d)"
  }
}

Note that in swift enum items should start with a lowercase letter so it should be fraction and mixed

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52