Swift converting between UInt and Int

后端 未结 5 1211
我寻月下人不归
我寻月下人不归 2020-12-30 18:52

I have the following methods

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

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

    return          


        
5条回答
  •  长情又很酷
    2020-12-30 19:31

    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)]
    }
    

提交回复
热议问题