Swift converting between UInt and Int Swift converting between UInt and Int ios ios

Swift converting between UInt and Int


In the first one, the return type is UInt, but you return Int since count returns Int.

Basically UInt has initializer which take variants of value types arguments such as Int, CGFloat, Double or event string and return a new value type.

  • UInt(8) // result is 8 UInt value type
  • UInt(20.12) // result is 20 UInt value type
  • UInt(Double(10)) // result is 10 UInt value type
  • UInt("10") // result is 10 UInt value type, note this is failable initializer, can be a value or nil

-

func numberOfPhotosInPhotoBrowser(photoBrowser: MWPhotoBrowser!) -> UInt {    return UInt(self.photos.count)}

For the second one, the array subscript expects Int value where you are passing UInt, so create a new Int value type from UInt,

func photoBrowser(photoBrowser: MWPhotoBrowser!, photoAtIndex index: UInt) -> MWPhotoProtocol! {    return self.photos[Int(index)]}


// initializing Intvar someInt: Int = 8someInt// Converting Int to UIntvar someIntToUInt: UInt = UInt(someInt)someIntToUInt// initializing UInt   var someUInt: UInt = 10someUInt// Converting UInt to Int   var someUIntToInt: Int = Int(someUInt)someUIntToInt


If you want unsigned int from negative value use UInt(bitPattern:)

let intVal = -1let uintVal = UInt(bitPattern: intVal) // uintVal == 0xffffffffffffffff