在
Swift中,类型注释用于使整数为double
let num: Double = 100 print(num)
为什么类型注释不能对double到整数执行相同的操作(错误不能将’Double’类型的值转换为指定类型’Int’)?
let num: Int = 100.0 print(num)
解决方法
将Int文字转换为Double只是因为Double符合
ExpressibleByIntegerLiteral
:
The standard library integer and floating-point types,such as Int and Double,conform to the ExpressibleByIntegerLiteral protocol. You can initialize a variable or constant of any of these types by assigning an integer literal.
要使第二个代码起作用,Int必须符合ExpressibleByFloatLiteral.
extension Int : ExpressibleByFloatLiteral { public typealias FloatLiteralType = Double public init(floatLiteral value: Int.FloatLiteralType) { self.init(value) } } let a: Int = 100.0 // works
我不特别推荐这样做.这可能会导致您意外地将double值传递给期望Int的函数,而不会让编译器抱怨.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。