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本身没有类型,它们会在编译器需要求值的时候被推断.