programing

Swift에서 사전에 요소를 추가하는 방법은 무엇입니까?

telebox 2023. 4. 22. 09:15
반응형

Swift에서 사전에 요소를 추가하는 방법은 무엇입니까?

다음과 같이 정의된 간단한 사전이 있습니다.

var dict : NSDictionary = [ 1 : "abc", 2 : "cde"]

이제 이 사전에 요소를 추가합니다.3 : "efg"

추가 방법3 : "efg"이 기존 사전으로 바꿀 수 있을까요?

사용하고 있다NSDictionary어떤 이유로 특별히 그런 타입이 필요한 경우가 아니라면 Swift 사전을 사용하는 것이 좋습니다.

Swift 사전을 예상하는 모든 함수에 전달할 수 있습니다.NSDictionary추가 작업 없이, 왜냐하면Dictionary<>그리고.NSDictionary서로 이음새 없이 연결되다네이티브 Swift 방식의 장점은 사전이 범용 유형을 사용한다는 것입니다.따라서 이 방법을 정의하면Int열쇠로서 그리고String다른 유형의 키와 값을 실수로 사용할 수 없습니다.(컴파일러가 사용자 대신 유형을 확인합니다.)

내가 당신의 코드에서 본 것을 바탕으로, 당신의 사전은Int열쇠로서 그리고String그 가치로.인스턴스를 만들고 나중에 항목을 추가하려면 다음 코드를 사용합니다.

var dict = [1: "abc", 2: "cde"] // dict is of type Dictionary<Int, String>
dict[3] = "efg"

나중에 다음 변수에 할당해야 하는 경우NSDictionary입력, 명시적 캐스트만 수행합니다.

let nsDict = dict as! NSDictionary

그리고 앞서 언급했듯이, 만약 당신이 그것을 기대하는 함수에 전달하고 싶다면NSDictionary캐스팅이나 변환 없이 그대로 전달합니다.

다음 방법으로 추가하고 변경할 수 있습니다.Dictionary로.NSMutableDictionary

dict["key"] = "value"

늦은 감이 있다는 걸 알지만 누군가에게 도움이 될 수도 있어따라서 키 값 쌍을 딕셔너리에 신속하게 추가하려면 다음과 같이 updateValue(값: , forKey: ) 방식을 사용할 수 있습니다.

var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)

SWIFT 3 - XCODE 8.1

var dictionary =  [Int:String]() 

dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)

사전에는 다음이 포함됩니다.

사전 [1: Hola, 2: Hello, 3: Aloha]

사전이 다음과 같은 경우Int로.String다음과 같이 간단하게 할 수 있습니다.

dict[3] = "efg"

사전의 에 요소를 추가하는 경우 가능한 해결 방법:

var dict = Dictionary<String, Array<Int>>()

dict["key"]! += [1]
dict["key"]!.append(1)
dict["key"]?.append(1)

스위프트 3 이상

사전에 새 값을 할당하는 예제입니다.NSMutableDictionary로 선언해야 합니다.

var myDictionary: NSMutableDictionary = [:]
let newValue = 1
myDictionary["newKey"] = newValue
print(myDictionary)
For whoever reading this for swift 5.1+

  // 1. Using updateValue to update the given key or add new if doesn't exist


    var dictionary = [Int:String]()    
    dictionary.updateValue("egf", forKey: 3)



 // 2. Using a dictionary[key]

    var dictionary = [Int:String]()    
    dictionary[key] = "value"



 // 3. Using subscript and mutating append for the value

    var dictionary = [Int:[String]]()

    dictionary[key, default: ["val"]].append("value")

Swift에서 NSDictionary를 사용하는 경우setValue:

dict.setValue("value", forKey: "key")

다음과 같은 두 개의 사전이 제공됩니다.

var dic1 = ["a": 1, "c": 2]
var dic2 = ["e": 3, "f": 4]

dic2부터 dic1까지 모든 아이템을 추가하는 방법은 다음과 같습니다.

dic2.forEach {
   dic1[$0.key] = $0.value
}

Dict.updateValue사전에서 기존 키의 값을 업데이트하거나 키가 존재하지 않는 경우 새 키와 값의 쌍을 추가합니다.

예-

var caseStatusParams: [String: AnyObject] = ["userId" : UserDefault.userID ]
caseStatusParams.updateValue("Hello" as AnyObject, forKey: "otherNotes")

결과 -

▿  : 2 elements
    - key : "userId"
    - value : 866
▿  : 2 elements
    - key : "otherNotes"
    - value : "Hello"

Swift 5 에서는, 다음의 코드 수집이 기능합니다.

 // main dict to start with
 var myDict : Dictionary = [ 1 : "abc", 2 : "cde"]

 // dict(s) to be added to main dict
 let myDictToMergeWith : Dictionary = [ 5 : "l m n"]
 let myDictUpdated : Dictionary = [ 5 : "lmn"]
 let myDictToBeMapped : Dictionary = [ 6 : "opq"]

 myDict[3]="fgh"
 myDict.updateValue("ijk", forKey: 4)

 myDict.merge(myDictToMergeWith){(current, _) in current}
 print(myDict)

 myDict.merge(myDictUpdated){(_, new) in new}
 print(myDict)

 myDictToBeMapped.map {
     myDict[$0.0] = $0.1
 }
 print(myDict)

[문자열:[임의]

를 사용하는 동료에게[String:Any]대신Dictionary아래는 내선번호입니다.

extension Dictionary where Key == String, Value == Any {
    
    mutating func append(anotherDict:[String:Any]) {
        for (key, value) in anotherDict {
            self.updateValue(value, forKey: key)
        }
    }
}

새 요소를 추가하려면 방금 설정한 항목:

listParameters["your parameter"] = value

사전에 데이터를 추가하는 기능은 없습니다.기존 사전의 새 키에 대해 값을 할당하기만 하면 됩니다.사전에 자동으로 가치가 추가됩니다.

var param  = ["Name":"Aloha","user" : "Aloha 2"]
param["questions"] = "Are you mine?"
print(param)

출력은 다음과 같습니다.

["이름" :"알로하" "알로하2" "질문" "넌 내 거야?""]

새 키-값 쌍을 사전에 추가하려면 키 값을 설정하기만 하면 됩니다.예를 들어,

// Initialize the Dictionary
var dict = ["name": "John", "surname": "Doe"]
 
// Add a new key with a value

dict["email"] = "john.doe@email.com"

print(dict)

력 ->["surname": "Doe", "name": "John", "email": "john.doe@email.com"]

var dict = ["name": "Samira", "surname": "Sami"]
// Add a new enter code herekey with a value
dict["email"] = "sample@email.com"
print(dict)

지금까지 Swift의 상위 기능 중 하나를 사용하여 사전에 데이터를 추가하는 가장 좋은 방법은 다음과 같습니다.'아쉬운'다음 코드 스니펫을 따릅니다.

newDictionary = oldDictionary.reduce(*newDictionary*) { r, e in var r = r; r[e.0] = e.1; return r }

@Dharmesh 당신의 경우는,

newDictionary = dict.reduce([3 : "efg"]) { r, e in var r = r; r[e.0] = e.1; return r }

위의 구문을 사용하는 데 문제가 있으면 알려주세요.

Swift 5 해피 코딩

var tempDicData = NSMutableDictionary()

for temp in answerList {
    tempDicData.setValue("your value", forKey: "your key")
}

사전 확장자를 추가했습니다.

extension Dictionary {   
  func cloneWith(_ dict: [Key: Value]) -> [Key: Value] {
    var result = self
    dict.forEach { key, value in result[key] = value }
    return result  
  }
}

하면 .cloneWith

 newDictionary = dict.reduce([3 : "efg"]) { r, e in r.cloneWith(e) }

NSDictionary를 수정 또는 업데이트하려면 먼저 NSMutableDictionary로 형식 캐스팅하십시오.

let newdictionary = NSDictionary as NSMutableDictionary

그럼 간단하게 사용하세요.

 newdictionary.setValue(value: AnyObject?, forKey: String)

언급URL : https://stackoverflow.com/questions/27313242/how-to-append-elements-into-a-dictionary-in-swift

반응형