简体   繁体   English

SWIFT-'double'不能转换为'string'

[英]SWIFT - 'double' not convertible to 'string'

I am learning the Swift language and I want to make a label equal what the PickerView has selected. 我正在学习Swift语言,并且想要使标签等于PickerView选择的标签。 I am making a countdown timer to learn the language and to learn about timing with the NSTimer. 我正在制作一个倒数计时器,以学习该语言并学习有关NSTimer的计时。 I am trying to convert the number, which is a double, to a string, which would be the UILabel. 我正在尝试将双精度数转换为字符串,即UILabel。

This is what I have for the PickerView. 这就是我的PickerView。 //UIPickerView // UIPickerView

var numbers = [1.00, 2.00, 3.00, 4.00, 5.00, 6.00, 7.00,8.00, 9.00, 10.00, 11.00,12.00, 13.00, 14.00, 15.00, 16.00, 17.00, 18.00, 19.00, 20.00]


func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
    return 1
}

func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    return numbers.count
}

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
    return numbers[row]
}

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int){

    subtractNumbers(\(numbers))

}

func subtractNumbers(number: Double) -> Double {
    return number - 0.01
}

I have researched a little bit and I am pretty sure I have to format it somehow. 我做了一些研究,我很确定我必须以某种方式格式化它。 Any help is appreciated. 任何帮助表示赞赏。 Please explain your answers! 请解释您的答案!

Issue is with the following function: 问题在于以下功能:

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
{
    return numbers[row]
}

The return type of thee function in String but you are returning a Double . String中thee函数的返回类型,但是您将返回Double

Change it like: 像这样更改它:

func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String!
{
    return "\(numbers[row])";
}

Also there is one more issue in your following code: 您的以下代码中还有一个问题:

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
    subtractNumbers(\(numbers))
}

You are passing an entire array instead of selected value. 您正在传递整个数组,而不是所选值。 So change the code like: 因此,更改代码如下:

func pickerView(pickerView: UIPickerView!, didSelectRow row: Int, inComponent component: Int)
{
    subtractNumbers(numbers[row])
}

This is how you convert a number to a string. 这是将数字转换为字符串的方式。

var number = 1.0
var string = "\(number)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM