Swift 类型转换 [英] Swift type conversions

查看:22
本文介绍了Swift 类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部:

根据 Swift Programming 一书,p.52,下面的代码不应该工作,因为 x 是 Int64 而 y 显然是 Int16,但 Swift playground 批准了.

According to the Swift Programming book, p. 52, the code below should not work because x is Int64 and y is obviously Int16, yet the Swift playground approves.

var x:Int = 32
var y:Int16 = 12

x + y

如果我使用 -、* 或/,编译器会反对,那么这是一个错误吗?如果不是,那么 + 有什么不同?

If I use -, * or /, the compiler does object, so is this a bug? If not, what's different about +?

迈克尔

推荐答案

+ 运算符有两个通用声明,可以处理一侧的 Strideable 值和一个值在与第一个值的 Stride 别名匹配的另一侧.它在这种情况下有效,因为 (a) Int16 通过 RandomAccessIndexType 符合 Strideable,并且 IntInt16 和所有其他整数类型的 >stride 别名.

The + operator has two generic declarations that can handle a Strideable value on one side and a value on the other side that matches the first value's Stride alias. It works in this case because (a) Int16 conforms to Strideable via RandomAccessIndexType, and Int is the Stride alias for Int16 and all the other integer types.

换句话说,您正在调用这些函数中的第一个,而不是第二个:

In other words, you're calling the first of these functions, not the second:

// Int on the left, Int16 on the right:
func +<T : Strideable>(lhs: T.Stride, rhs: T) -> T

// Int16 would have to be on both sides:
func +(lhs: Int16, rhs: Int16) -> Int16

文档: Int16 类型+ 运算符Strideable 协议.

Documentation: Int16 type, + operator, Strideable protocol.

这篇关于Swift 类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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