# Type erasure with failable initializer?

**URL:** <https://forums.swift.org/t/type-erasure-with-failable-initializer/34110>\
**Category:** Using Swift\
**Tags:** generics, associatedtype, type-erasure\
**Created:** [February 26, 2020, 1:18pm UTC](https://forums.swift.org/t/type-erasure-with-failable-initializer/34110 "2020-02-26T13:18:32Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![dsmitchell](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/dsmitchell/32/7552_2.png) [@dsmitchell](https://forums.swift.org/u/dsmitchell)\
**Post date:** [February 26, 2020, 1:18pm UTC](https://forums.swift.org/t/type-erasure-with-failable-initializer/34110/1 "2020-02-26T13:18:32Z")

</div>

Hi all, I'm struggling with trying to complete this puzzle, and all the examples of type erasure I found did not include a use-case with a failable initializer. Here is the example:

```
/// Contrived example of protocol
protocol Choosable {
	/// Another way of saying enum that is an Int or String and can be iterated
	associatedtype Choice: RawRepresentable, CaseIterable
	/// prints the choices of the implementing type (I know Choice is not used anywhere here)
	func printChoices()
}

/// A required base class in this example with desired use-case
class CommonClass {
	func someMethod() {
            // This is how I'd like to use the not-yet-built AnyChoosable()
		guard let choosable = AnyChoosable(self) else { return }
		choosable.printChoices()
	}
}

/// Creates a default implementation of Choosable.printChoices() for CommonClass
extension Choosable where Self: CommonClass, Choice: CaseIterable, Choice.RawValue == String {
	func printChoices() {
		Choice.allCases.forEach { choice in
			print("\(Self.self).choice = \(choice)")
		}
	}
}

class ASubclass: CommonClass {
	/// Defining a specific Choice
	enum Choice: String, CaseIterable {
		case this
		case that
	}
}

```

Main question: What is an implementation of AnyChoosable (with failable initializer) that implements a Choosable?

Alternative question: Perhaps Choice can better be rewritten to more clearly specify the desired kind of enum, and maybe printChoices() is instead a method called on the Choice?

Thanks so much!
