source

스위프트의 사전에서 키의 값을 얻으려면 어떻게 해야 합니까?

factcode 2023. 10. 26. 21:53
반응형

스위프트의 사전에서 키의 값을 얻으려면 어떻게 해야 합니까?

스위프트 사전을 가지고 있습니다.저는 제 열쇠 값을 받고 싶습니다.키 메소드의 개체가 제게 맞지 않습니다.사전 키 값은 어떻게 구합니까?

이것은 내 사전입니다.

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for name in companies.keys { 
    print(companies.objectForKey("AAPL"))
}

사전 키의 값에 액세스하려면 첨자를 사용합니다.그러면 옵션이 반환됩니다.

let apple: String? = companies["AAPL"]

아니면

if let apple = companies["AAPL"] {
    // ...
}

모든 키와 값에 걸쳐 열거할 수도 있습니다.

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    print("\(key) -> \(value)")
}

또는 모든 값을 열거합니다.

for value in Array(companies.values) {
    print("\(value)")
}

Apple Documents에서

첨자 구문을 사용하여 특정 키에 대한 사전에서 값을 검색할 수 있습니다.값이 없는 키를 요청할 수 있기 때문에 사전의 첨자는 사전의 값 유형 중 선택적 값을 반환합니다.사전에 요청한 키에 대한 값이 포함된 경우 첨자는 해당 키에 대한 기존 값이 포함된 선택적 값을 반환합니다.그렇지 않으면 첨자가 0을 반환합니다.

https://developer.apple.com/documentation/swift/dictionary

if let airportName = airports["DUB"] {
    print("The name of the airport is \(airportName).")
} else {
    print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."

값을 찾으려면 아래를 사용하십시오.

if let a = companies["AAPL"] {
   // a is the value
}

사전을 횡단하는 경우

for (key, value) in companies {
    print(key,"---", value)
}

값으로 키를 검색하려면 먼저 확장자를 추가합니다.

extension Dictionary where Value: Equatable {
    func findKey(forValue val: Value) -> Key? {
        return first(where: { $1 == val })?.key
    }
}

그럼 그냥 전화해요.

companies.findKey(val : "Apple Inc")
var dic=["Saad":5000,"Manoj":2000,"Aditya":5000,"chintan":1000]

print("salary of Saad id \(dic["Saad"]!)")

사전의 멤버들에게 접근하기 위해서 당신은 반드시 !를 포함해야 합니다. (느낌)
!=> 힘에 대한 문서 압축 풀기 세부사항을 의미합니다.

언급URL : https://stackoverflow.com/questions/25741114/how-can-i-get-keys-value-from-dictionary-in-swift

반응형