Swift 2.0 - 如何从字符串输入

时间:2015-11-22 21:49:20

标签: tuples swift2

我正在学习用树屋编写Swift 2.0代码。我正在尝试编写一个代码,您可以在其中输入“艾菲尔铁塔”,“大金字塔”,“悉尼歌剧院”,该功能将输出经度和纬度坐标。我无法让函数返回坐标 - 任何帮助都将不胜感激!

func getTowerCoordinates (location: String) -> (lat: Double, lon: Double) {
switch location {
case "Eiffel Tower": (48.8582, 2.2945)
case "Great Pyramid": (29.9792, 31.1344)
case "Sydney Opera House": (33.8587, 151.2140)
default: (0,0)
}
return (lat, lon)

}

1 个答案:

答案 0 :(得分:1)

首先,您应该创建一个变量,您可以在其中保存数据然后将其返回。

func getTowerCoordinates (location: String) -> (lat: Double, lon: Double) {
    var coordinates: (lat: Double, lon: Double)

    switch location {
    case "Eiffel Tower":
        coordinates = (48.8582, 2.2945)
        break
    case "Great Pyramid":
        coordinates = (29.9792, 31.1344)
        break
    case "Sydney Opera House":
        coordinates = (33.8587, 151.2140)
        break
    default:
        coordinates = (0,0)
    }

    return coordinates
}

或更容易:

func getTowerCoordinates (location: String) -> (lat: Double, lon: Double) {
    switch location {
    case "Eiffel Tower":
        return (48.8582, 2.2945)
    case "Great Pyramid":
        return (29.9792, 31.1344)
    case "Sydney Opera House":
        return (33.8587, 151.2140)
    default:
        return (0, 0)
    }
}

(lat: Double, lon: Double)是函数的结果类型,您可以将元组的第一个元素标记为lat,将第二个元素标记为lon

之后,你可以这样写:

let (lat, lon) = getTowerCoordinates("Eiffel Tower") 
print(lat)
print(lon)

let coordinates = getTowerCoordinates("Eiffel Tower")
print(coordinates.lat)
print(coordinates.lon)

是相同的