Итерация по массиву Swift и изменение значений

Для этого я использовал бы SimpleXML . Это выглядело бы так:

// Open and parse the XML file
$xml = simplexml_load_file("questions.xml");
// Create a child in the first topic node
$child = $xml->topic[0]->addChild("subtopic");
// Add the text attribute
$child->addAttribute("text", "geography");

Вы можете либо отобразить новый код XML с помощью эха, либо сохранить его в файле.

// Display the new XML code
echo $xml->asXML();
// Store new XML code in questions.xml
$xml->asXML("questions.xml");

-1
задан Mike Nathas 3 March 2019 в 20:05
поделиться

3 ответа

Я нашел простой способ и хотел бы поделиться им.

Ключом является определение myArray. Это было бы успешным, если бы это было так:

 let myArray : [NSMutableDictionary] = [["firstDict":1, "otherKey":1], ["secondDict":2, "otherKey":1], ["lastDict":2, "otherKey":1]]

 myArray.enumerated().forEach{[110].element["index"] = [110].offset}

 print(myArray)






 [{
firstDict = 1;
index = 0;
otherKey = 1;
 }, {
index = 1;
otherKey = 1;
secondDict = 2;
}, {
index = 2;
lastDict = 2;
otherKey = 1;
}]
0
ответ дан E.Coms 3 March 2019 в 20:05
поделиться

Как насчет более функционального подхода путем создания нового массива для хранения измененных словарей:

let myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]
let myNewArray = myArray.enumerated().map { index, _ in ["index": index] }
0
ответ дан Code Different 3 March 2019 в 20:05
поделиться

Счетчик в цикле for является константой. Чтобы сделать его изменчивым, вы можете использовать:

for var item in myArray { ... }

Но это не поможет, поскольку мы будем мутировать item, а не элементы в myArray.

Вы можете изменить элементы в myArray следующим образом:

var myArray = [["index": 0], ["index":0], ["index":0], ["index":0]]

var counter = 0

for i in myArray.indices {
    myArray[i]["index"] = counter
    counter += 1
}

print(myArray) //[["index": 0], ["index": 1], ["index": 2], ["index": 3]]

Переменная counter здесь не нужна:

for i in myArray.indices {
    myArray[i]["index"] = i
}

A Функциональный способ написания вышесказанного будет:

myArray.indices.forEach { myArray[[113]]["index"] = [113] }
0
ответ дан ielyamani 3 March 2019 в 20:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: