Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Swift (iOS app), when do I need to use other integer types?

Tags:

swift

I saw there are many integer types in Swift other than Int, for example:

Int8
UInt32
uint_fast16_t

I can understand their definitions but I am wondering when/why I should use them instead of Int?

For example, Int8 is a 8-bit integer. From my understanding, unless I want to save some memory, why bother using it?

PS. I am using Swift for iOS app development.

like image 599
Joe Huang Avatar asked Dec 16 '15 00:12

Joe Huang


2 Answers

In the same way that Swift has other aspects underneath the covers such as pointers, these other numeric types are there for specific purposes. Some of these purposes are:

  • Integration with a C library. There may be specific C types that a C library requires and these types allow you to pass data to/from the libraries

  • Very large scientific datasets. Float (32-bit single precision floating point) allows you to keep twice the elements in memory in the same space as Double at some sacrifice to accuracy. Multi-day global environmental datasets from satellite sensors, astronomy datasets, etc. have huge space requirements.

  • Half-precision floating point requires half the storage and bandwidth of Float and can be pertinent for some graphics applications

  • Vector processing using the Accelerate library. Accelerate functions work with a variety of numeric types and 32-bit single precision accuracy may be acceptable for the task you wish to accomplish.

like image 152
timbo Avatar answered Oct 20 '22 16:10

timbo


Like others have mentioned, sometimes there is a need for interoperability with some external (C) library, or you just want to put constraints on the values allowed/detect overflow.

As an example, consider this gist I made some time ago:

import UIKit

extension UIColor
{
    convenience init(
        redByte   red:UInt8,
        greenByte green:UInt8,
        blueByte  blue:UInt8,
        alphaByte alpha:UInt8
        )
    {
        self.init(
            red:   CGFloat(red  )/255.0,
            green: CGFloat(green)/255.0,
            blue:  CGFloat(blue )/255.0,
            alpha: CGFloat(alpha)/255.0
        )
    }
}

...which is a convenient short-hand for creating a UIColor instance when you know the values of components you want to use as 'bytes' (integers in the 0-255 range), instead of 'normalized' floats (i.e., 0.0 ~ 1.0).

Using the specific type UInt8 instead of Swift's native Int enforces the policy (and clarifies the intent) that arguments should be unsigned, 8 bit integer values.

like image 38
Nicolas Miari Avatar answered Oct 20 '22 17:10

Nicolas Miari