combine two array each element and append to one array [duplicate] - ios

This question already has answers here:
How to merge two arrays in Swift
(3 answers)
Closed 3 years ago.
I have two array like below. I need to combine two array each data and append to one array. The example are :
var d1 = ["1", "2", "3", "4", "5"]
var d2 = ["A", "B", "C", "D", "E"]
var d3 = [String]()
//O/P needed : ["1-A","2-B","3-C","4-D","5-E"]
Any help would be great.
Thanks

Use a combination of zip(_:_:) and map(_:) over d1 and d2 like so,
let d3 = zip(d1, d2).map({ $0.0 + "-" + $0.1})
print(d3) //["1-A", "2-B", "3-C", "4-D", "5-E"]
In case any one of the arrays have extra elements, those extra ones will be ignored while performing the zip operation.

var d1 = ["1", "2", "3", "4", "5"]
var d2 = ["A", "B", "C", "D", "E"]
var d3 = [String]()
//O/P needed : ["1-A","2-B","3-C","4-D","5-E"]
// works for diff length of d2
func mergArray(firstArray: [String], secondArray: [String]) -> [String] {
for (index,val) in d1.enumerated() {
guard index < d2.count else {
d3.append(val)
return d3
}
d3.append(val + "-" + d2[index])
}
return d3
}
print(mergArray(firstArray: d1, secondArray: d2))

Do it like -
for i in 0..< d1.count {
d3.append(d1[i] + "-" + d2[i])
}
print(d3)
You will have your desire result.

Related

Swift iOS XOR with a conversion from UInt8 to Int

This is code has been driving me crazy, it's so simple but cannot get it to work. I have followed several examples and help from the forum, but the XOR is not working. The problem is when I extract the char from the string array and convert it to an ASCII value it's a Uint8 rather than an Int. So the XOR does not work, how can I convert an Uint8 to an int?
// Convert the data into the string
for n in 0...7
{
print("Inside the password generator for loop /(n)")
let a:Character = SerialNumber_hex_array[n]
var a_int = a.asciiValue
let b:Character = salt_arrary[n]
let b_int = b.asciiValue
// This does not work as the a_int & b_int are not int !!!
// How to convert the Uint8 to int?
let xor = (a_int ^ b_int)
// This code works
var a1 = 12
var b1 = 25
var result = a1 ^ b1
print(result) // 21
}
To convert your UInt8? to Int, use an available Int initializer:
let a_int = Int(a.asciiValue!)
let b_int = Int(b.asciiValue!)
let xor = (a_int ^ b_int) // compiles
This direct approach requires force unwrapping but I assume the hex array looks like below and your characters are hard coded for safety. If not, unwrap these unsigned integers safely with if-else or guard.
let SerialNumber_hex_array: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]

Combining 2 Array into dictionary [duplicate]

This question already has answers here:
Swift equivalent to `[NSDictionary initWithObjects: forKeys:]`
(5 answers)
Closed 3 years ago.
I want to combine 2 array.
arr1 = ["a", "b", "c"]
arr2 = ["1", "2", "3"]
i want to make it to be :
"a" = "1"
"b" = "2"
"c" = "3"
so if i call value "1" into label1, it means value "a" is also called into label2 just like dictionary or index.
Just like that:
let arr1 = ["a", "b", "c"]
let arr2 = ["1", "2", "3"]
let dictionary = Dictionary(uniqueKeysWithValues: zip(arr1, arr2))
It's one line code
let dict = zip(["a", "b", "c"], ["1", "2", "3"]).compactMap{[$0.0:$0.1]}.reduce([:]) { $0.merging($1) { (current, _) in current } }
print(dict)
["a": "1", "b": "2", "c": "3"]
I suggests you to use user28434's answer which is more effective than mine. I am keeping my answer as alternative second best solution

How can I change the order of two arrays when one array is sorted? [duplicate]

This question already has answers here:
In Swift how can I sort one array based on another array?
(4 answers)
Closed 4 years ago.
If I have:
var arrayOne = ["dog", "cat", "hamster", "horse"]​
and
var arrayTwo = [3, 2, 4, 1]
How can I assign 3 to dog, 2 to cat, 4 to hamster, and 1 to horse so that if I sort arrayTwo from biggest integer to smallest, it will automatically do that for arrayOne too. In result it would print out:
var arrayOne = ["hamster", "dog", "cat", "horse"]
var arrayTwo = [4, 3, 2, 1]
What code is easiest and simplest for this?
Thanks in Advance! :)
It's quite hard to "bind" the two variables together. You could do something like this:
let dict = [3: "dog", 2: "cat", 4: "hamster", 1: "horse"]
var arrayTwo = [3, 2, 4, 1] {
willSet {
// you should probably check whether arrayTwo still has the same elements here
arrayOne = newValue.map { dict[$0]! }
}
}
It is easier to zip the arrays and then sort by arrayTwo:
let result = zip(arrayOne, arrayTwo).sorted(by: { $0.1 > $1.1 })
Now, result.map { $0.0 } is your sorted array 1 and result.map { $0.1 } is your sorted array 2.

Swift array map with comma before append new value

i have this following data structure in my Realm object
var tags = List<Tag>()
"tags": [
{
"tagId": "80069",
"tagName": "A"
},
{
"tagId": "80070",
"tagName": "B"
},
{
"tagId": "80071",
"tagName": "C"
},
{
"tagId": "80073",
"tagName": "D"
}
]
So what i want to achieve is, I map all my tag name into my new array
this is my code
let realmObject = self.realm.objects(MyDTO.self)
let array = Array(realmOutletList).map{Array($0.tags).map{$0.tagName!}.joined(separator: ",")}
it prints out this
["A,B,C", "A,C,D", "B,C,D"]
What I want to achieve is like
["A","B","C", "A","C","D", "B","C","D"]
I need that kind of array because I am going to create a Set from the array and then compare with another array
The compared array will be like
["A","B","C", "A","C","D", "B","C","D"]
because of the compared Array and the realmObject Array is different, it always shows false when i use
let subset = filterSet.isSubset(of: mySet)
Can anyone guide me please??
Thanks
Let's walk through solving the issue:
Consider that you have:
let originalArray = ["A,B,C", "A,C,D", "B,C,D"]
First, we need to separate each string in originalArray by "," character, so we could do:
let modifiedArray = originalArray.map { $0.components(separatedBy: ",") }
We map it to transform each string to a strings array (separation).
So far, the output of modifiedArray would be:
[["A", "B", "C"], ["A", "C", "D"], ["B", "C", "D"]]
which is an array of strings array.
Second, we need to spilt each -string- array in modifiedArray (having one reduced strings array instead), so we could do:
var final = [String]()
for array in modifiedArray {
for string in array {
final.append(string)
}
}
OR by using reduce
let finalArray = modifiedArray.reduce([], +)
Therefore, finalArray would be:
["A", "B", "C", "A", "C", "D", "B", "C", "D"]
which is the desired result.
Conclusion
For a fully one-lined answer (following the high-order functions approach):
let originalArray = ["A,B,C", "A,C,D", "B,C,D"]
let desiredArray = originalArray.map { $0.components(separatedBy: ",") }.reduce([], +)
print(desiredArray) // ["A", "B", "C", "A", "C", "D", "B", "C", "D"]
Well, it's quite easy:
This
let array = Array(realmOutletList).map{Array($0.tags).map{$0.tagName!}.joined(separator: ",")}
should be this
let array = Array(realmOutletList).flatMap{Array($0.tags).map{$0.tagName!}}
That's all. And you will get your ["A","B","C", "A","C","D", "B","C","D"].

How to add element at Last index Swift

I am getting an Array from server and I store it in NSMutableArray. Now the issue is that the Array is not sorted. For eg. array = ["A","B","None","C","D"]. I want to sort it and place the "None" element at last. i.e ["A","B","C","D","None"]. Tried swapping but was unable to match the condition, as the array may increase in future. Check my code below which is not working as expected.
if array.containsObject( "None" ){
print("\(array.indexOfObject("None"))")
let noneIndex = array.indexOfObject("None")
print(noneIndex)
array.removeObject(noneIndex)
print("Remove Array:-\(array)")
array.insertObject(noneIndex, atIndex: (array.lastObject?.index)!)
print("Sorted Array:-\(array)")
}
Maybe I'm misunderstanding what it is that you need to do, but you could use sorted() on your array if you just want to sort it alphabetically.
You could also use filter to remove "None" from your array, sort it, and then append "None" as the last element
For instance, if you have
let elements = ["Alpha", "Bold", "None", "charlie", "Delta", "echo", "zebra", "k"]
You could start out by filtering it:
let filteredElements = elements.filter { $0.uppercased() != "NONE"}
Sort the filtered elements:
var sortedElements = filteredElements.sorted { $0.uppercased() < $1.uppercased()}
Append "None"
sortedElements.append("None") // ["Alpha", "Bold", "charlie", "Delta", "echo", "k", "zebra", "None"]
And be done.
Here it is combined:
let lastElement = "None"
let elements = ["Alpha", "Bold", "None", "charlie", "Delta", "echo", "zebra", "k"]
var sortedElements = elements.filter({$0.uppercased() != lastElement.uppercased()}).sorted(by: {$0.uppercased() < $1.uppercased()})
sortedElements.append(lastElement)
Hope that helps you.
var array = ["A", "B", "None", "C", "D"]
if let noneIndex = array.index(of: "None") {
array.remove(at: noneIndex)
array.append("None")
}
print(array)
This should move None at the end of the array, and sort the other elements:
let ["A", "B", "None", "C", "D"]
array.sorted { $1 == "None" || $0 < $1 } // ["A", "B", "C", "D", "None"]
This simply takes benefits of the by argument that can be passed to the sort/sorted method from Array.
Edit #MartinR had a very strong point regarding the comparison predicate from this answer, which indeed doesn't offer a strong weak ordering. Sorting the array with a correct predicate would be along the lines of:
array.sorted { $0 == "None" ? false : $1 == "None" ? true : $0 < $1 }
This will work:
// starting test array
let array = ["B", "None", "C","P","None","A", "Q"]
var sorted = array.sorted { (str1, str2) -> Bool in
return str1 < str2
}
sorted.forEach { str in
if str == "None" {
if let idx = sorted.index(of: str) {
sorted.remove(at: idx)
sorted.append(str)
}
}
}
// Sorted array is now ["A", "B", "C", "P", "Q", "None", "None"]

Resources