Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift converting between UInt and Int

Tags:

int

ios

swift

I have the following methods

var photos = [MWPhoto] = [MWPhoto]()

func numberOfPhotosInPhotoBrowser(photoBrowser: MWPhotoBrowser!) -> UInt {

    return self.photos.count
}

func photoBrowser(photoBrowser: MWPhotoBrowser!, photoAtIndex index: UInt) -> MWPhotoProtocol! {

    return self.photos[index]
}

However for the first I get Int is not convertible to UInt (since self.photos.count is an Int

and for the second UInt is not convertible to Int - since the self.photos[ can only take an Int for its index.

How can I correctly convert the UInt to Int and back?

like image 637
Tarang Avatar asked Sep 28 '14 15:09

Tarang


3 Answers

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)]
}
like image 78
Sandeep Avatar answered Nov 17 '22 01:11

Sandeep


// initializing Int
var someInt: Int = 8
someInt

// Converting Int to UInt
var someIntToUInt: UInt = UInt(someInt)
someIntToUInt

// initializing UInt   
var someUInt: UInt = 10
someUInt

// Converting UInt to Int   
var someUIntToInt: Int = Int(someUInt)
someUIntToInt
like image 26
appdevelopersspotlight Avatar answered Nov 17 '22 03:11

appdevelopersspotlight


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

let intVal = -1
let uintVal = UInt(bitPattern: intVal) // uintVal == 0xffffffffffffffff
like image 6
coldfire Avatar answered Nov 17 '22 02:11

coldfire