在UInt和Int之间快速转换 [英] Swift converting between UInt and Int

查看:761
本文介绍了在UInt和Int之间快速转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下方法

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

但是对于第一个我得到 Int不能转换为UInt (因为 self.photos.count 是一个 Int

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

和第二个 UInt不能转换为Int - 因为 self.photos [只能为其索引获取Int。

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

如何正确转换UInt到Int和back?

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

推荐答案

在第一个中,返回类型是 UInt ,但是你返回Int,因为count返回Int。

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

基本上,UInt具有初始化程序,它接受值类型参数的变体,如Int,CGFloat,Double或事件字符串,并返回一个新的值类型。

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) //结果是8 UInt值类型

  • UInt(20.12) //结果是20 UInt值类型

  • UInt(Double(10)) //结果是10 UInt v alue type

  • UInt(10) //结果是10个UInt值类型,注意这是可用的初始值设定项,可以是值或者为零

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

对于第二个,数组下标需要传递 UInt 的Int值,因此从 UInt 创建一个新的 Int 值类型,

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

这篇关于在UInt和Int之间快速转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆