[swift-evolution] Why can't protocols define constants or subtypes?

Charles Srstka cocoadev at charlessoft.com
Wed May 11 12:33:55 CDT 2016


With a class or a struct, I can nest constants and subtypes within the type, like so:

class MyWidget {
	static let SomeConstant = “This string is useful to subclasses of MyWidget somehow"
	
	enum Type {
		case Cog
		case Sprocket
	}

	enum Error {
		case SomethingWentWrong
		case SomethingElseWentWrong
	}

	var type: Self.Type // This doesn’t work yet, but it should after SE-0068 is implemented

	func doSomething() throws // might throw one of the errors above
}

This is nice for namespacing, and it makes the code clear and organized.

However, if I convert this to a protocol-based approach, I have to do this the old Objective-C way:

static let MyWidgetSomeConstant = “This string is useful to implementers of MyWidget somehow"

enum MyWidgetType {
	case Cog
	case Sprocket
}

enum MyWidgetError {
	case SomethingWentWrong
	case SomethingElseWentWrong
}

protocol MyWidget {
	var type: MyWidgetType

	func doSomething() throws // might throw one of the errors above
}

This is ugly, and pollutes the global namespace with things that are only interesting to users and implementers of MyWidget. Is there a reason behind this? It seems that it could be useful to define constants and subtypes that could be useful for implementers of a protocol.

Charles



More information about the swift-evolution mailing list