[swift-dev] Set of "no less than one" member enforced by the compiler

Brent Royal-Gordon brent at architechies.com
Sun Jun 26 14:46:03 CDT 2016


> Half-digression into relational theory aside, I can’t figure a way to make the compiler enforce this. An enum is "exactly one", a Set is "zero or more", a structure or class is "this group", an Optional is "zero or one".

You can write an enum that's "one or more":

	enum OneOrMore<Element> {
		case one (Element)
		indirect case more (first: Element, rest: OneOrMore<Element>)
	}

Or, equivalently:

	struct OneOrMore<Element> {
		var first: Element
		var rest: [Element]
	}

`first` could instead be `last`, of course; I've done it this way because `reduce` is a left fold.

It should be possible to conform either of these to Collection or even MutableCollection, but not to RangeReplaceableCollection, which assumes you can create an empty instance.

-- 
Brent Royal-Gordon
Architechies



More information about the swift-dev mailing list