How to combine multiple seperate json results from loop then return swiftHow to call Objective-C code from SwiftHow return data from an HTTP request in Swift/Objective CAlamofire, SwiftyJSON update UI after receiving responseTableView not displaying text with JSON data from API callHow to show images from API in CollectionViewCall api using alomafier request get data inside a response but below request it get blankHow to create a block response like Alamofire Responses?How to return an object from a method that contains a DataTaskHow do I make a custom completion handler?Having trouble decoding JSON in Swift 4

Should I disclose a colleague's illness (that I should not know) when others badmouth him

NIntegrate doesn't evaluate

Is Jon Snow the last of his House?

Externally monitoring CPU/SSD activity without software access

Why aren't space telescopes put in GEO?

I unknowingly submitted plagarised work

Employer asking for online access to bank account - Is this a scam?

What are these arcade games in Ghostbusters 1984?

What to keep in mind when telling an aunt how wrong her actions are, without creating further family conflict?

Popcorn is the only acceptable snack to consume while watching a movie

What to do when you've set the wrong ISO for your film?

Why were helmets and other body armour not commonplace in the 1800s?

Sitecore 9.0 works with solr 7.2.1?

Compaq Portable vs IBM 5155 Portable PC

How should I introduce map drawing to my players?

Which European Languages are not Indo-European?

Does Nitrogen inside commercial airliner wheels prevent blowouts on touchdown?

What does this symbol on the box of power supply mean?

Why is this Simple Puzzle impossible to solve?

Why are C64 games inconsistent with which joystick port they use?

What are the real benefits of using Salesforce DX?

Apache redirect to https:/www only partially working

How to deal with a colleague who is being aggressive?

Is it true that cut time means "play twice as fast as written"?



How to combine multiple seperate json results from loop then return swift


How to call Objective-C code from SwiftHow return data from an HTTP request in Swift/Objective CAlamofire, SwiftyJSON update UI after receiving responseTableView not displaying text with JSON data from API callHow to show images from API in CollectionViewCall api using alomafier request get data inside a response but below request it get blankHow to create a block response like Alamofire Responses?How to return an object from a method that contains a DataTaskHow do I make a custom completion handler?Having trouble decoding JSON in Swift 4






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I want to combine 3 json results into one for looping into later.



I have tried every single combination on the internet yet I'm still stuck a dead end. I am calling an API call that in response, receives json data. I want to get the first 3 results and return that data to the calling method however, I just cannot find a way to find the desired response.



var data: JSON = []

func getData(forKey url: URL, completion: @escaping ([JSON]) -> Void)

AF.request(url).responseJSON (responseData) -> Void in
if((responseData.result.value) != nil)
let swiftyJsonVar = JSON(responseData.result.value!)
for loopID in 0 ... 2
print(swiftyJsonVar["results"][loopID])


return completion([self.data])




My desired results are



[

"name": "james",
"location": "Mars"
,

"name": "james",
"location": "Mars"
,

"name": "james",
"location": "Mars"

]


When, in my loop, I receive, x 3




"name": "james",
"location": "Mars"










share|improve this question




























    1















    I want to combine 3 json results into one for looping into later.



    I have tried every single combination on the internet yet I'm still stuck a dead end. I am calling an API call that in response, receives json data. I want to get the first 3 results and return that data to the calling method however, I just cannot find a way to find the desired response.



    var data: JSON = []

    func getData(forKey url: URL, completion: @escaping ([JSON]) -> Void)

    AF.request(url).responseJSON (responseData) -> Void in
    if((responseData.result.value) != nil)
    let swiftyJsonVar = JSON(responseData.result.value!)
    for loopID in 0 ... 2
    print(swiftyJsonVar["results"][loopID])


    return completion([self.data])




    My desired results are



    [

    "name": "james",
    "location": "Mars"
    ,

    "name": "james",
    "location": "Mars"
    ,

    "name": "james",
    "location": "Mars"

    ]


    When, in my loop, I receive, x 3




    "name": "james",
    "location": "Mars"










    share|improve this question
























      1












      1








      1








      I want to combine 3 json results into one for looping into later.



      I have tried every single combination on the internet yet I'm still stuck a dead end. I am calling an API call that in response, receives json data. I want to get the first 3 results and return that data to the calling method however, I just cannot find a way to find the desired response.



      var data: JSON = []

      func getData(forKey url: URL, completion: @escaping ([JSON]) -> Void)

      AF.request(url).responseJSON (responseData) -> Void in
      if((responseData.result.value) != nil)
      let swiftyJsonVar = JSON(responseData.result.value!)
      for loopID in 0 ... 2
      print(swiftyJsonVar["results"][loopID])


      return completion([self.data])




      My desired results are



      [

      "name": "james",
      "location": "Mars"
      ,

      "name": "james",
      "location": "Mars"
      ,

      "name": "james",
      "location": "Mars"

      ]


      When, in my loop, I receive, x 3




      "name": "james",
      "location": "Mars"










      share|improve this question














      I want to combine 3 json results into one for looping into later.



      I have tried every single combination on the internet yet I'm still stuck a dead end. I am calling an API call that in response, receives json data. I want to get the first 3 results and return that data to the calling method however, I just cannot find a way to find the desired response.



      var data: JSON = []

      func getData(forKey url: URL, completion: @escaping ([JSON]) -> Void)

      AF.request(url).responseJSON (responseData) -> Void in
      if((responseData.result.value) != nil)
      let swiftyJsonVar = JSON(responseData.result.value!)
      for loopID in 0 ... 2
      print(swiftyJsonVar["results"][loopID])


      return completion([self.data])




      My desired results are



      [

      "name": "james",
      "location": "Mars"
      ,

      "name": "james",
      "location": "Mars"
      ,

      "name": "james",
      "location": "Mars"

      ]


      When, in my loop, I receive, x 3




      "name": "james",
      "location": "Mars"







      swift swifty-json






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 3:35









      James BJames B

      156




      156






















          1 Answer
          1






          active

          oldest

          votes


















          1














          For starters, I'd put in a breakpoint and see what your response object looks like from whatever endpoint you're hitting. Perhaps those really are the first three elements of the array?



          Moving along to the matter at hand, I would use the Codable protocol for decoding your response. I'll skip the Alamofire part and focus solely on decoding the object. Using your example, here's what the struct would look like:



          struct ResponseObject: Codable 
          let name: String
          let location: String



          I would avoid using the bang operator (!) in your code, as you'll throw an exception if you tell the compiler it's 100% guaranteed money in the bank the object's not nil and it actually is. Instead, unwrap optionals.



          You'll need a landing spot for your decoded data, so you could declare an empty array of responses, as follows:



          var arrayOfObjects: [ResponseObject] = []


          Then, you'd just declare a decoder and decode your data:



          let decoder = JSONDecoder()

          do
          if let data = rawData
          arrayOfObjects = try decoder.decode([ResponseObject].self, from: data)
          print("number of objects:", arrayOfObjects.count)
          let slice = arrayOfObjects.prefix(3)
          arrayOfObjects = Array(slice)
          print("number of objects after slicing the array:", arrayOfObjects.count)

          catch
          print(error)



          Instead of looping through the array, just grab the first three elements of the array with .prefix(3). Fiddling with this just now, I tried prefixing the first 10 elements of an array with 4 and it didn't generate an exception, so I think that should work without checking the count of the array first.



          I would suggest taking a look through Swift documentation online re: Arrays or you could get a pretty sweet Mac OS app called Dash that lets you load up docsets for a bunch of languages on your machine locally.



          Good luck!






          share|improve this answer

























          • Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

            – James B
            Mar 24 at 4:46











          • @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

            – Harshal Wani
            Mar 24 at 4:55











          • @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

            – James B
            Mar 24 at 5:32











          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320512%2fhow-to-combine-multiple-seperate-json-results-from-loop-then-return-swift%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          For starters, I'd put in a breakpoint and see what your response object looks like from whatever endpoint you're hitting. Perhaps those really are the first three elements of the array?



          Moving along to the matter at hand, I would use the Codable protocol for decoding your response. I'll skip the Alamofire part and focus solely on decoding the object. Using your example, here's what the struct would look like:



          struct ResponseObject: Codable 
          let name: String
          let location: String



          I would avoid using the bang operator (!) in your code, as you'll throw an exception if you tell the compiler it's 100% guaranteed money in the bank the object's not nil and it actually is. Instead, unwrap optionals.



          You'll need a landing spot for your decoded data, so you could declare an empty array of responses, as follows:



          var arrayOfObjects: [ResponseObject] = []


          Then, you'd just declare a decoder and decode your data:



          let decoder = JSONDecoder()

          do
          if let data = rawData
          arrayOfObjects = try decoder.decode([ResponseObject].self, from: data)
          print("number of objects:", arrayOfObjects.count)
          let slice = arrayOfObjects.prefix(3)
          arrayOfObjects = Array(slice)
          print("number of objects after slicing the array:", arrayOfObjects.count)

          catch
          print(error)



          Instead of looping through the array, just grab the first three elements of the array with .prefix(3). Fiddling with this just now, I tried prefixing the first 10 elements of an array with 4 and it didn't generate an exception, so I think that should work without checking the count of the array first.



          I would suggest taking a look through Swift documentation online re: Arrays or you could get a pretty sweet Mac OS app called Dash that lets you load up docsets for a bunch of languages on your machine locally.



          Good luck!






          share|improve this answer

























          • Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

            – James B
            Mar 24 at 4:46











          • @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

            – Harshal Wani
            Mar 24 at 4:55











          • @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

            – James B
            Mar 24 at 5:32















          1














          For starters, I'd put in a breakpoint and see what your response object looks like from whatever endpoint you're hitting. Perhaps those really are the first three elements of the array?



          Moving along to the matter at hand, I would use the Codable protocol for decoding your response. I'll skip the Alamofire part and focus solely on decoding the object. Using your example, here's what the struct would look like:



          struct ResponseObject: Codable 
          let name: String
          let location: String



          I would avoid using the bang operator (!) in your code, as you'll throw an exception if you tell the compiler it's 100% guaranteed money in the bank the object's not nil and it actually is. Instead, unwrap optionals.



          You'll need a landing spot for your decoded data, so you could declare an empty array of responses, as follows:



          var arrayOfObjects: [ResponseObject] = []


          Then, you'd just declare a decoder and decode your data:



          let decoder = JSONDecoder()

          do
          if let data = rawData
          arrayOfObjects = try decoder.decode([ResponseObject].self, from: data)
          print("number of objects:", arrayOfObjects.count)
          let slice = arrayOfObjects.prefix(3)
          arrayOfObjects = Array(slice)
          print("number of objects after slicing the array:", arrayOfObjects.count)

          catch
          print(error)



          Instead of looping through the array, just grab the first three elements of the array with .prefix(3). Fiddling with this just now, I tried prefixing the first 10 elements of an array with 4 and it didn't generate an exception, so I think that should work without checking the count of the array first.



          I would suggest taking a look through Swift documentation online re: Arrays or you could get a pretty sweet Mac OS app called Dash that lets you load up docsets for a bunch of languages on your machine locally.



          Good luck!






          share|improve this answer

























          • Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

            – James B
            Mar 24 at 4:46











          • @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

            – Harshal Wani
            Mar 24 at 4:55











          • @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

            – James B
            Mar 24 at 5:32













          1












          1








          1







          For starters, I'd put in a breakpoint and see what your response object looks like from whatever endpoint you're hitting. Perhaps those really are the first three elements of the array?



          Moving along to the matter at hand, I would use the Codable protocol for decoding your response. I'll skip the Alamofire part and focus solely on decoding the object. Using your example, here's what the struct would look like:



          struct ResponseObject: Codable 
          let name: String
          let location: String



          I would avoid using the bang operator (!) in your code, as you'll throw an exception if you tell the compiler it's 100% guaranteed money in the bank the object's not nil and it actually is. Instead, unwrap optionals.



          You'll need a landing spot for your decoded data, so you could declare an empty array of responses, as follows:



          var arrayOfObjects: [ResponseObject] = []


          Then, you'd just declare a decoder and decode your data:



          let decoder = JSONDecoder()

          do
          if let data = rawData
          arrayOfObjects = try decoder.decode([ResponseObject].self, from: data)
          print("number of objects:", arrayOfObjects.count)
          let slice = arrayOfObjects.prefix(3)
          arrayOfObjects = Array(slice)
          print("number of objects after slicing the array:", arrayOfObjects.count)

          catch
          print(error)



          Instead of looping through the array, just grab the first three elements of the array with .prefix(3). Fiddling with this just now, I tried prefixing the first 10 elements of an array with 4 and it didn't generate an exception, so I think that should work without checking the count of the array first.



          I would suggest taking a look through Swift documentation online re: Arrays or you could get a pretty sweet Mac OS app called Dash that lets you load up docsets for a bunch of languages on your machine locally.



          Good luck!






          share|improve this answer















          For starters, I'd put in a breakpoint and see what your response object looks like from whatever endpoint you're hitting. Perhaps those really are the first three elements of the array?



          Moving along to the matter at hand, I would use the Codable protocol for decoding your response. I'll skip the Alamofire part and focus solely on decoding the object. Using your example, here's what the struct would look like:



          struct ResponseObject: Codable 
          let name: String
          let location: String



          I would avoid using the bang operator (!) in your code, as you'll throw an exception if you tell the compiler it's 100% guaranteed money in the bank the object's not nil and it actually is. Instead, unwrap optionals.



          You'll need a landing spot for your decoded data, so you could declare an empty array of responses, as follows:



          var arrayOfObjects: [ResponseObject] = []


          Then, you'd just declare a decoder and decode your data:



          let decoder = JSONDecoder()

          do
          if let data = rawData
          arrayOfObjects = try decoder.decode([ResponseObject].self, from: data)
          print("number of objects:", arrayOfObjects.count)
          let slice = arrayOfObjects.prefix(3)
          arrayOfObjects = Array(slice)
          print("number of objects after slicing the array:", arrayOfObjects.count)

          catch
          print(error)



          Instead of looping through the array, just grab the first three elements of the array with .prefix(3). Fiddling with this just now, I tried prefixing the first 10 elements of an array with 4 and it didn't generate an exception, so I think that should work without checking the count of the array first.



          I would suggest taking a look through Swift documentation online re: Arrays or you could get a pretty sweet Mac OS app called Dash that lets you load up docsets for a bunch of languages on your machine locally.



          Good luck!







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 24 at 5:25

























          answered Mar 24 at 4:21









          AdrianAdrian

          8,881864134




          8,881864134












          • Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

            – James B
            Mar 24 at 4:46











          • @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

            – Harshal Wani
            Mar 24 at 4:55











          • @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

            – James B
            Mar 24 at 5:32

















          • Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

            – James B
            Mar 24 at 4:46











          • @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

            – Harshal Wani
            Mar 24 at 4:55











          • @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

            – James B
            Mar 24 at 5:32
















          Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

          – James B
          Mar 24 at 4:46





          Initializer for conditional binding must have Optional type, not 'JSON' where it says ``` let data = rawData``` -- I changed rawData to my response JSON.

          – James B
          Mar 24 at 4:46













          @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

          – Harshal Wani
          Mar 24 at 4:55





          @JamesB you already checked rawData while declaration using guard. Just remove if let data = rawData condition and replace data with rawData

          – Harshal Wani
          Mar 24 at 4:55













          @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

          – James B
          Mar 24 at 5:32





          @HarshalWani Nothing I try works. I use the responseData which just results in this error: Cannot convert value of type 'DataResponse<Any>' to expected argument type 'Data'

          – James B
          Mar 24 at 5:32



















          draft saved

          draft discarded
















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid


          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.

          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55320512%2fhow-to-combine-multiple-seperate-json-results-from-loop-then-return-swift%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          용인 삼성생명 블루밍스 목차 통계 역대 감독 선수단 응원단 경기장 같이 보기 외부 링크 둘러보기 메뉴samsungblueminx.comeh선수 명단용인 삼성생명 블루밍스용인 삼성생명 블루밍스ehsamsungblueminx.comeheheheh

          155 수학 과학 기타 둘러보기 메뉴eh추가해eh문서를 완성해