title: Why does the Swift language guide suggest using Int "even when values are known to be non-negative"?
body: <p>This is a question about programming style in Swift, specifically <code>Int</code> vs <code>UInt</code>.</p>
  
  <p>The Swift Programming Language Guide advises programmers to use the generic signed integer type <code>Int</code> even when variables are known to be non-negative. From <a href="https://developer.apple.com/library/prerelease/ios/documentation/swift/conceptual/swift_programming_language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_411">the guide</a>:</p>
  
  <blockquote>
    <p>Use UInt only when you specifically need an unsigned integer type with the same size as the platform’s native word size. If this is not the case, Int is preferred, even when the values to be stored are known to be non-negative. A consistent use of Int for integer values aids code interoperability, avoids the need to convert between different number types, and matches integer type inference, as described in Type Safety and Type Inference.</p>
  </blockquote>
  
  <p>However, <code>UInt</code> will be 32-bit unsigned on 32-bit architectures and 64-bit unsigned on 64-bit architectures so there is no performance benefit to using <code>Int</code> over <code>UInt</code>.</p>
  
  <p>By contrast, the Swift guide gives a later example:</p>
  
  <blockquote>
    <p>let age = -3<br>
    assert(age >= 0, "A person's age cannot be less than zero")<br>
    // this causes the assertion to trigger, because age is not >= 0  </p>
  </blockquote>
  
  <p>Here, a <em>runtime</em> issue could be caught at <em>compile</em> time if the code had been written as:</p>
  
  <pre><code>let age:UInt = -3  
  // this causes a compiler error because -3 is negative
  </code></pre>
  
  <p>There are many other cases (for example anything that will index a collection) where using a <code>UInt</code> would catch issues at compile time rather than runtime.</p>
  
  <p>So the question: is the advice in the Swift Programming Language guide sound, and do the benefits of using <code>Int</code> "even when the values to be stored are known to be non-negative" outweigh the safety advantages of using <code>UInt</code>?</p>
  
  <p><strong>Additional note:</strong> Having used Swift for a couple of weeks now its clear that for interoperability with <em>Cocoa</em> <code>UInt</code> is required. For example the <code>AVFoundation</code> framework uses unsigned integers anywhere a "count" is required (number of samples / frames / channels etc). Converting these values to <code>Int</code> could lead to serious bugs where values are greater than <code>Int.max</code></p>