如何在int和float之间的算术在Swift? [英] How to do arithmetic between int and float in Swift?

查看:2310
本文介绍了如何在int和float之间的算术在Swift?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在Swift编程中的第一天,直到现在我们使用Objective C.我试图编写简单的添加程序。喜欢,

  var i = 10 
var j = 10
var k = i + j
println(k)

但是当我将其中一个值改为float时,

  var i = 10 
var j = 10.4
var k = i + j
println(k)




错误:main.swift:13:找不到'+'的重载
接受提供的参数


现在我做了Google搜索,例如 Double(i + j),但它不工作。 Swift应该在这种情况下将int隐式转换为float,不是吗?



请注意我是否对Swift语言有任何误解。

解决方案

根据你想要的结果,你应该使用类型init方法将其转换为适当的类型。 / p>

例如

  var myInt = 5; 
var myDouble = 3.4;

如果我想要一个double例如在我的结果

  var doubleResult = Double(myInt)+ myDouble; 

如果我想要一个整数,请注意double将被截断。

  var intResult = myInt + Int(myDouble)


b $ b

我在你的例子中看到的问题是你试图做一个add操作,然后转换它,但两个值需要相同,然后再执行添加。



苹果已经让它安静严格,以避免类型不匹配和转换错误。有时这可能有点'太严格'来自其他语言的开发,我很恼火,但我习惯了。


This is my first day in Swift programming and till now we are using Objective C. I tried to write simple addition program it works. Like,

var i = 10
var j = 10
var k = i + j
println(k)

But when I change one of the values to float it gives error.

var i = 10
var j = 10.4
var k = i + j
println(k)

Error: main.swift:13:11: Could not find an overload for '+' that accepts the supplied arguments

Now I did Google search and tried few thing e.g. Double(i+j) , but it doesn't work. Swift should implicitly convert int to float in this case, isn't it?

Please suggest if I am doing any mistake understanding Swift language.

解决方案

Depending on what you want your result to be, you should convert it to the appropriate type using that types init method.

eg.

var myInt = 5;
var myDouble = 3.4;

If I want a double for example in my result

var doubleResult = Double(myInt) + myDouble;

if I want an integer instead, please note the double will be truncated.

var intResult = myInt + Int(myDouble)

The problem I see in your example is you're trying to do an add operation and then convert it but both values needs to be the same before you perform the addition.

Apple has made it quiet strict to avoid type mis-match and conversion errors. Sometimes this can be a bit 'too strict' for dev coming from other languages, I was annoyed at first but I got used to it.

这篇关于如何在int和float之间的算术在Swift?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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