여기에 @vacawama의 대답 Dictionary
버전이 있습니다. 특정 유스 케이스를 더 좋게 (또는 나쁘게) 적용 할 수있는 대안입니다.
이 버전의 몇 가지 주목할만한 개선이 있습니다 사전에 열쇠를 찾고
- 입니다 매우 빠른 O (1), 배열에
find()
을 사용하면 매우 저조한 목록으로 성장함에 따라 수행으로 어디에 수백 개의 도시들 O (N).
- 문자열은 힙에 할당됩니다. 즉, 설계된 좌표
struct
은 성능면에서 (느린) class
과 유사하게 동작합니다. 귀하의 질문은 struct
에 위치 이름을 저장하는 강력한 사례를 제시하지 않았습니다.
먼저 좌표를 나타내는 구조체를 만듭니다.
print(coordinates["New York, NY"] ?? "Unknown Location”)
> "Coordinates(latitude: 40.713054, longitude: -74.007227999999998)”
:
struct Coordinate {
/// Latitude in decimal notation
let latitude: Double
/// Longitude in decimal notation
let longitude: Double
}
그런 다음
/// Empty mapping of location string to latitude-longitude
var coordinates = [String: Coordinate]()
가 여기에 사전을
/// Populate the locations
coordinates["New York, NY"] = Coordinate(latitude: 40.713054, longitude: -74.007228)
coordinates["Los Angeles, CA"] = Coordinate(latitude: 40.713054, longitude: -74.007228)
coordinates["Chicago, IL"] = Coordinate(latitude: 40.713054, longitude: -74.007228)
예 출력을 채우기 위해 한 가지 방법의 예 (귀하의 질문에 당) 빈 컬렉션을 만들
그게 다야! 조금 더
... 위치를 미리 알 수 있으며, 그 중 수백이없는 경우, 당신은 위해야 문자열 - 백업
enum
를 사용하여 시도 할 수있는 경우
원래의 질문에 대답하지만, Swift는 유형 시스템을 사용하여 더욱 흥미로운 접근법을 허용합니다.
Coordinate
의 숫자가 Double
인 것을 보장합니다. 그러나 위치의 무결성에 대한 보장은 없습니다. 나중에 실수로 coordinates[“New york, NY”]
을 입력 할 수 있습니다. "york"는 소문자이므로이 작업은 실패합니다! (또한 현재 게시 된 다른 답변도 있음).
enum Location: String {
case NY_NewYork = "New York, NY"
case CA_LosAngeles = "Los Angeles, CA"
case IL_Chicago = "Chicago, IL"
}
을 따라
/// Empty mapping of location string to latitude-longitude
var coordinates = [Location: Coordinate]()
/// Populate the locations
coordinates[.NY_NewYork] = Coordinate(latitude: 40.713054, longitude: -74.007228)
coordinates[.CA_LosAngeles] = Coordinate(latitude: 40.713054, longitude: -74.007228)
coordinates[.IL_Chicago] = Coordinate(latitude: 40.713054, longitude: -74.007228)
우리는 여전히 원래 "뉴욕, NY"제목이 우리의 사전 키 및 사용을 변경할 수 있지만 값 Location.NY_NewYork
로 정적으로 표현된다 : 여기에 열거입니다. 이것은 컴파일러가 실수를 범할 수 있음을 의미합니다!
한 가지 더 : 이제 위치가 정적 상수 값이되었으므로 실제로 힙 할당을 두 번 내지 않고 struct
안에 다시 넣을 수 있습니다! struct 값은 열거 형 값에 대한 참조입니다.
enum Location: String {
case NY_NewYork = "New York, NY"
case CA_LosAngeles = "Los Angeles, CA"
case IL_Chicago = "Chicago, IL"
}
struct Coordinate {
/// The logical name of the location referenced by this coordinate
let location: Location
/// Latitude in decimal notation
let latitude: Double
/// Longitude in decimal notation
let longitude: Double
}
/// Empty mapping of location string to latitude-longitude
var coordinates = [Location: Coordinate]()
/// Populate the locations
coordinates[.NY_NewYork] = Coordinate(location: .NY_NewYork, latitude: 40.713054, longitude: -74.007228)
coordinates[.CA_LosAngeles] = Coordinate(location: .CA_LosAngeles, latitude: 40.713054, longitude: -74.007228)
coordinates[.IL_Chicago] = Coordinate(location: .IL_Chicago, latitude: 40.713054, longitude: -74.007228)
// or if initializing from a data source, something like...
// if let loc = Location(rawValue: "Chicago, IL") {
// coordinates[loc] = Coordinate(location: loc, latitude: 40.713054, longitude: -74.007228)
// }
그리고 출력
print(coordinates[Location.NY_NewYork] ?? "uknown”)
> "Coordinate(location: Location.NY_NewYork, latitude: 40.713054, longitude: -74.007227999999998)”
쿨 :
여기에 최종 버전입니다! 이제 완벽한 유형 안전성, 거기에 위치 제목을 유지할 수있는 편의성 및 매우 고성능 아키텍처가 있습니다.
이것은 Swift를 iOS 용으로 사용하는 특별한 도구입니다.
사전의 배열입니다. 그러나 정적 필드의 배열을 저장하려고한다면 구조체의 배열이 필요합니다. – Hamish
* 팁 : * Option 키를 누른 상태에서 Xcode 소스 편집기의 'locations'를 클릭하면 해당 유형이 표시됩니다. (그러나 Hamish의 제안을 따르십시오.) –