Swift Generic "Numeric" Protocol that Validates Numeric Values
<p>Swift 3. </p>

<p>Ultimately my functions need to receive <code>UInt8</code> data types, but I'm never sure if the arguments I will receive from callers will be <code>Int</code>, <code>Int64</code>, <code>UInt</code>, <code>Float</code>, etc. I know they will be <strong>numeric</strong> types, I just don't know which flavor.</p>

<p>I could do:</p>

<pre><code>func foo(value: Int) { }
func foo(value: Float) {}
func foo(value: UInt) {}
</code></pre>

<p>But that's crazy. So I thought I could do something like create a protocol</p>

<pre><code>protocol ValidEncodable {
}
</code></pre>

<p>And then pass in types that conform:</p>

<pre><code>func foo(value: ValidEncodable) { }
</code></pre>

<p>And then in that function I could get my values into the correct format</p>

<pre><code>func foo(value: ValidEncoable) -&gt; UInt8 {
    let correctedValue = min(max(floor(value), 0), 100)
    return UInt8(correctedValue)
}
</code></pre>

<p>I'm really struggling to figure out </p>

<p>1) How to create this ValidEncodable protocol that contains all the <em>numeric</em> types</p>

<p>2) And how to do things like floor(value) when the value I get is an Int without iterating over every possible numeric type (i.e. (floor(x) is only available on floating-point types) </p>

<p>Ultimately I need the values to be UInt8 in the range of 0-100. The whole reason for this madness is that I'm parsing XML files to my own internal data structures and I want to bake in some validation to my values.</p>