PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, May 13, 2022

[FIXED] How do I merge and format arrays in Swift? (X and Y coordinate arrays)

 May 13, 2022     append, arrays, ios, merge, swift     No comments   

Issue

I am attempting to merge two arrays in specific formatting in order to create an array of x and y coordinates that will be used to create a graph. I have separate arrays of X-Values and Y-Values in [Double] format, for example:

var xAxis = [1, 2, 3, 4]
var yAxis = [2, 3, 4, 5]

I wish to merge these such that they are presented in the following format:

var chartPoints = [(1,2),(2,3),(3,4),(4,5)]

or more generally:

chartPoints = [(x,y)]

I have tried a few different options, such as the append and extend methods to no luck as this does not sort the arrays or format them in the method required.

How can I merge the two x and y axis arrays to a singular formatted array?


Solution

You can use the zip global function, which, given 2 sequences, returns a sequence of tuples:

let pointsSequence = zip(xAxis, yAxis)

You can then obtain an array of tuples by using the proper init:

let chartPoints = Array(pointsSequence)

Each element of the array is a (x, y) tuple - but values are unnamed, so you can access their individual values by index:

let point = chartPoints[0]
point.0 // This is the 1st element of the tuple
point.1 // This is the 2nd element of the tuple

If you prefer the tuple values to be named, you can make the tuple type explicit:

let chartPoints: [(x: Int, y: Int)] = Array(pointsSequence)

and with that you can access using either the index (as in the example above) or using their explicit names:

let point = chartPoints[0]
point.x
point.y


Answered By - Antonio
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing