加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Swift Compiler Error Binary oprator '+' cann

发布时间:2020-12-14 02:03:21 所属栏目:百科 来源:网络整理
导读:1. Swift报错: Swift Compiler Error Binary oprator '+' cannot be applied to operands of type 'UInt16' and 'UInt8' 错误写法: let a: UInt16 = 1_000 let b: UInt8 = 1 let sum = a + b println ( "sum = ( sum )" ) 错误原因: 不同类型的变量和常量

1. Swift报错: Swift Compiler Error Binary oprator '+' cannot be applied to operands of type 'UInt16' and 'UInt8'

错误写法:

let a:UInt16 = 1_000

let b: UInt8 =1

let sum = a + b

println("sum = (sum)")


错误原因: 不同类型的变量和常量可以存储不同范围的数字.如果数字超出了可存储的范围,编译的时候会报错.所以你必须根据不同情况选择性使用数值类型转换.

正确写法:

let a:UInt16 = 1_000

let b: UInt8 =1

let sum = a + UInt16(b)

println("sum = (sum)")


2. Swift报错: Swift Compiler Error Binary oprator '+' cannot be applied to operands of type 'Int' and 'Double'

错误写法:

let a = 123

let b = 0.456

let sum = a + b

println("sum = (sum)")

错误原因: 加好两边的数的类型必须相同,不能直接相加.所以int和double类型不能直接相加.

正确写法:

let a = 123

let b = 0.456

let sum = Double(a) + b

println("sum = (sum)")


注意: 区别 let sum = 123 + 0.456相这样写是正确的,因为数字字面量123本身没有类型,它们会在编译器需要求值的时候被推断.

以上的 Double(a) UInt16(b) 这样的someType(ofInitialValue)是调用Swift构造器并传入一个初始化的默认方法.在语言内部,UInt16有一个构造器,可以接收一个UInt8类型的值,所以这个构造器可以用现有的UInt8来创建一个新的UInt16.注意你并不能传入任意的值,只能传入UInt16内部有对应构造器的值.不过你可以扩展现有的类型来让它可以接收其他类型的值(包括自定义的类型)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读