Как добавить / вставить элемент в массив один за другим, как стек Swift 5 - PullRequest
1 голос
/ 02 октября 2019

Я получаю строку из ответа API и сохраняюсь в массиве.

     for customParams in custom_attributes! {
         if(customParams["attribute_code"] as! String == "small_image") 
        {
         print(customParams["value"])
         var myString = customParams["value"] as! String

         //want to add this myString in array(myArray) one after another
         var myArray :[String] = []
              print(myArray)      
        }
 }

Вывод:

myArray = ["myString1","myString2"......]

Как мне это сделать, ребята? Я все еще новичок в Swift ... Заранее спасибо!

"id": 6,
"products": {
"items": [{
"status": 1,
"custom_attributes": [
{
{
"attribute_code": "small_image",
"value": "small_image"
},
{
"attribute_code": "meta_keyword",
"value": "meta_keyword"
}]},
{
"status": 1,
"custom_attributes": [
{
{
"attribute_code": "small_image",
"value": "small_image"
},
{
"attribute_code": "meta_keyword",
"value": "meta_keyword"
}
]}]}}]

хочу получить customParams ["attribute_code"] == small_image

Ответы [ 2 ]

1 голос
/ 02 октября 2019

Сначала вам нужно перебрать массив элементов, как это делается в json, также объявить myArray вне цикла for и начать добавлять myString в myArray, как показано:

var myArray :[String] = []
for custom_attributes! in items { // items is the json items array
    for customParams in custom_attributes! {
        if(customParams["attribute_code"] as! String == "small_image") 
             {
             print(customParams["value"])
             var myString = customParams["value"] as! String
             myArray.append(myString)

         }
     }
 }
0 голосов
/ 02 октября 2019
var myArray :[String] = []

for customParams in custom_attributes! {    
    if(customParams["attribute_code"] as! String == "small_image") {
         var myString = customParams["value"] as! String
         myArray.append(myString)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...