2015-11-22 44 views
0

我正在學習用treehouse編寫Swift 2.0代碼。我想寫一個代碼,你可以進入「艾菲爾鐵塔」,「大金字塔」,「悉尼歌劇院」,並且該函數會輸出經度和緯度座標。我遇到麻煩的功能返回座標 - 任何幫助將不勝感激!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

首先,你應該創建一個變量,你可以保存數據,然後返回。

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) 

這是相同