错误:通用参数'元素'无法推断

时间:2016-07-07 12:05:00

标签: ios swift casting nsarray

以下代码执行将输入coordinate与多个预定义coordinates进行比较的功能。但是,当我尝试将其中一个coordinates的字符串值转换为float时,它会出现"错误:泛型参数'元素'无法推断"。

我想将数组的字符串元素转换为float

import UIKit

var coordinates: [[[String]]] = []
var nodeLetter:Array=["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
var nextValue = ""
var checkCoordinates = ["",""] 
var distance = 100000
var xDifference = 0.0
coordinates = [[["A","0.000","0.000"]],[["B","55.5352431","58.4545"]],[["C","0.000","200.123"]]]

var inputCooridnate = ["65.123","62.0909"]

for amount in coordinates {
    for elements in amount { 
        for items in elements{

            if nextValue == "Y"{
                checkCoordinates[1] = items
                print("Y Value = \(items)")
                nextValue = ""
                print(("Pie= \(Double(inputCooridnate[0]))"))
                xDifference =Double(inputCooridnate[0])
            }

            if nextValue == "X"{
                checkCoordinates[0] = items
                print("X Value = \(items)")
                nextValue = "Y"
            }

            if nodeLetter.contains(items) {
                print("Start Node \(items)")
                nextValue = "X"
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

请您尝试更改

xDifference =Double(inputCooridnate[0])

使用

guard let xDifference = Double(inputCooridnate[0]) else {
    fatalError("Please check coordinates - cannot be nil")
}

为了防止出现nil值,使用?符号来表示它可能包含nil值。换句话说,它成为可选的。如果以后要使用它,则需要将其解包(使用!),因此宣誓具有价值。一种替代方法是使用guard let-'可选绑定'的示例-一种更安全,更好的方法来防止值为零的情况。 请让我知道此解决方案是否有效。祝一切顺利!