# Use Swift's type system to restrict values

**URL:** <https://forums.swift.org/t/use-swifts-type-system-to-restrict-values/70919>\
**Category:** Using Swift\
**Created:** [March 26, 2024, 3:05pm UTC](https://forums.swift.org/t/use-swifts-type-system-to-restrict-values/70919 "2024-03-26T15:05:57Z")\
**Posts on this page:** 1\
**Showing post:** 18

<div class="post-metadata">

**Author:** ![wadetregaskis](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/wadetregaskis/32/8494_2.png) [@wadetregaskis](https://forums.swift.org/u/wadetregaskis)\
**Post date:** [March 27, 2024, 8:52pm UTC](https://forums.swift.org/t/use-swifts-type-system-to-restrict-values/70919/18 "2024-03-27T20:52:46Z")

</div>

> [@tera](#):
>
> ```swift
> var x: [Int?] = ... // 16 bytes per element
> var y: [IntX?] = ... // 8 bytes per element
> 
> ```

To elaborate for those that might be confused by these numbers, this is referring back to [Memory-optimal collections of Optionals](https://forums.swift.org/t/memory-optimal-collections-of-optionals/70237). Giving up even just a single value in the `Element`'s space allows (in principle) `Optional` to use that to represent `nil`, thus saving it from having to have a separate boolean flag and therefore unintentionally doubling the size of each `Array` because of the need to maintain correct alignment for `Element`.

> [@Joe\_Groff](#):
>
> enums are a great fit for when you have a limited number of valid values

Not just limited, but _very small_. Because defining explicit enum cases for e.g. the range of `Int`, would be not just comically inefficient in size (on the order of a hundred billion billion bytes of source code) but practically guaranteed to never compile (due to super-linear compile-times for enums based on their member count).

Even a more "plausible" scenario like a mere `Int8`-sized thing would be many kilobytes of code just for the cases, not even counting the various helper methods to convert to actual numeric values. So we're talking tens of kilobytes of source to express the notion `typealias DomainSpecificInt = UInt8 where Self ~= 0...250`.

And even if all of that isn't a showstopper, the ergonomics of enums for numeric values are horrible - you have to manually conform them to all the relevant numeric protocols, which is a _lot_ of surface area (just try implementing your own `FixedWidthInteger` and see how many dozens and dozens of methods & properties that requires).

---

_[View the full topic](https://forums.swift.org/t/use-swifts-type-system-to-restrict-values/70919)._
