How can I remove values array based on array other [duplicate] - arrays

This question already has answers here:
Set operations (union, intersection) on Swift array?
(5 answers)
Closed 5 years ago.
How can I remove values array based on array other.
Example :-
Type ( Int )
var arrayOne = [1,2,3,4,5,6,7,8]
var arrayTwo = [1,2,4,5,6,7]
I want the next result :-
result = [3,8]

User Set for simple result
var arrayOne = [1,2,3,4,5,6,7,8]
var arrayTwo = [1,2,4,5,6,7]
let set1:Set<Int> = Set(arrayOne)
let set2:Set<Int> = Set(arrayTwo)
let set3 = set1.symmetricDifference(set2)
Output :
{3, 8}

You can do it by converting them to Sets.
var arrayOne = [1,2,3,4,5,6,7,8]
var arrayTwo = [1,2,4,5,6,7]
let set1:Set<String> = Set(arrayOne)
let set2:Set<String> = Set(arrayTwo)
Use ExclusiveOr to do this.
//Swift 2.0
set1.exclusiveOr(array2) // result = {3,8}
//Swift 3.0
set1.symmetricDifference(set2) // result = {3,8}
This link might useful for you: Set operations (union, intersection) on Swift array?
also possible Duplicate as #user3589771 said.

You can do with below options.
// Option 1 - Using Set's
let arrayOne : Set = [1,2,3,4,5,6,7,8]
let arrayTwo : Set = [1,2,4,5,6,7]
var result = arrayOne.symmetricDifference(arrayTwo)
print(result) // {3,8}
// Option 2 - Using Array
var result1 = [Int]()
for value in arrayOne
{
if !arrayTwo.contains(value)
{
result1.append(value)
}
}
print(result1) // {3,8}

Use following working code -
let arrayOne = [1,2,3,4,5,6,7,8]
let arrayTwo = [1,2,4,5,6,7]
var result = [Int]()
for value in arrayOne
{
if !arrayTwo.contains(value)
{
result.append(value)
}
}

Related

merging element of two different arrays into dictionary in swift

i have two arrays like these
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
i want to create a new dictionary that have first element of first array and first element of second array and so on. when the third element of first array comes it should again get the first element of second array.
for example:-
dict = ["han" : "hello", "Ji" : "Ji", "Kidda" : hello, "Ho" : "Ji", "Tusi" : "hello"]
If the second array has 2 items you can do
var dict = [String: String]()
for (index, item) in arr1.enumerated() {
dict[item] = arr2[index % 2]
}
I believe this is what you're looking for (using arr1 as the keys and arr2 as the values repeating them as necessary):
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
let dict = Dictionary(uniqueKeysWithValues: zip(arr1, arr1.indices.map { arr2[$0 % arr2.count] }))
print(dict)
["Kidda": "hello", "Ji": "Ji", "han": "hello", "Ho": "Ji", "Tusi": "hello"]
Note:
Dictionaries have no specified ordering. Only the key/value pairings matter. This matches the example in your question.
Explanation:
zip is used to create a sequence of (key, value) tuples from two sequences that will become the key/value pairs for the new Dictionary. The keys come from arr1. map is used to generate the sequence of values from arr2 repeating them as many times as necessary to match the count of arr1. This sequence of (key, value) tuples is passed to Dictionary(uniqueKeysWithValues:) to turn that sequence into the desired Dictionary.
try:
var dict = ["arr1" : "hello", "arr2" : "Ji"]
then for third you can append by
dict[3] = ["arr3" : String(arr3.first())]
Try this:
var arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
var arr2 = ["hello", "Ji"]
var dict : [String : String] = [:]
var arr2Index = 0
for index in 0..<arr1.count {
let arr1Value = arr1[index]
if arr2Index == arr2.count {
arr2Index = 0
}
let arr2Value = arr2[arr2Index]
dict[arr1Value] = arr2Value
arr2Index += 1
}
Here's a fun way:
let arr1 = ["han", "Ji", "Kidda", "Ho", "Tusi"]
let arr2 = ["hello", "Ji"]
let arr3 = Array(repeating: arr2, count: arr1.count).joined()
let d = zip(arr1,arr3).reduce(into: [String:String]()) { $0[$1.0] = $1.1 }

how to remove specific element from 2D Array in swift [duplicate]

This question already has answers here:
How to remove an element from an array in Swift
(18 answers)
Closed 4 years ago.
I have a [[String]] like
myArr = [["1_2","1_3","1_4"], ["2_1","2_2","2_3"], ["3_1","3_2","3_3"]] then
I Want to remove element like this
bypassArr = ["1_2","2_3","3_2"]
how to remove bypassArr from myArr using element. or how can i get this type of result.
result = [["1_3","1_4"], ["2_1","2_2"], ["3_1","3_3"]]
If the intention is to remove all elements from bypassArr in the “inner” arrays from myArr then a combination of map() and filter() does the trick:
let myArr = [["1_2","1_3","1_4"], ["2_1","2_2","2_3"], ["3_1","3_2","3_3"]]
let bypassArr = ["1_2","2_3","3_2"]
let result = myArr.map { innerArray in
innerArray.filter { elem in
!bypassArr.contains(elem)
}
}
print(result)
// [["1_3", "1_4"], ["2_1", "2_2"], ["3_1", "3_3"]]
The inner arrays are filtered to remove the given elements, and the outer array is mapped to the filtered results.
Or with short-hand parameter notation:
let result = myArr.map { $0.filter { !bypassArr.contains($0) }}
var myArr = [["1_2","1_3","1_4"], ["2_1","2_2","2_3"], ["3_1","3_2","3_3"]]
let bypassArr = ["1_2","2_3","3_2"]
if myArr.count == bypassArr.count {
myArr = bypassArr.enumerated().map({ (index, str) -> [String] in
if let strPos = myArr[index].firstIndex(of: str) {
myArr[index].remove(at: strPos)
}
return myArr[index]
})
}
print(myArr)

How to update swift dictionary value

I rewrite this code from php. And I find it difficult to make it work in swift.
var arrayOfData = [AnyObject]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
let data = d as AnyObject
// I want to update the "count" value
// data["count"] = 8
print(data);
break;
}
Presumably, you want to update the value inside of arrayOfData when you assign data["count"] = 8. If you switch to using NSMutableArray and NSMutableDictionary, then your code will work as you want. The reason this works is that these types are reference types (instead of value types like Swift arrays and dictionaries), so when you're working with them, you are referencing the values inside of them instead of making a copy.
var arrayOfData = NSMutableArray()
for index in 1...5 {
var dict = NSMutableDictionary()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.addObject(dict)
}
for d in arrayOfData {
let data = d as! NSMutableDictionary
data["count"] = 8
print(data)
break
}
Assuming your array has to be of form '[AnyObject]' then something like this:
var arrayOfData = [AnyObject]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
// check d is a dictionary, else continue to the next
guard let data = d as? [String: AnyObject] else { continue }
data["count"] = 8
}
But preferably your array would be typed as an array of dictionaries:
var arrayOfData = [[String: AnyObject]]()
for index in 1...5 {
var dict = [String: AnyObject]()
dict["data"] = [1,2,3]
dict["count"] = 0
arrayOfData.append(dict)
}
for d in arrayOfData {
// swift knows that d is of type [String: AnyObject] already
d["count"] = 8
}
EDIT:
So the issue is that when you modify in the loop, you're creating a new version of the dictionary from the array and need to transfer it back. Try using a map:
arrayOfData = arrayOfData.map{ originalDict in
var newDict = originalDict
newDict["count"] = 8
return newDict
}
The most efficient way would be to find the index of the relevant values entry, and then replace that entry. The index is essentially just a pointer into the hash table, so it's better than looking up by key twice:
To update all the entries, you can loop through the indices one at a time:
for i in dictionary.values.indices {
dictionary.values[i].property = ...
}
To update a particular key, use:
let indexToUpdate = dictionary.values.index(forKey: "to_update")
dictionary.values[i].property = ...

Swift: Get multiple array values like "x"

For example, I have an array like var myArray = ['player_static.png', 'player_run0.png', 'player_run1.png', 'player_run2.png', 'player_jump0.png', 'player_jump1.png']
Is there any simple way to get only the "player_runX.png" images?
You can use filter to get all elements that hasPrefix("player_run"):
let myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
let playerRuns = myArray.filter{$0.hasPrefix("player_run")}
print(playerRuns) //["player_run0.png", "player_run1.png", "player_run2.png"]
One way to do this would be to iterate over the array and retrieve the elements that match the pattern. A very quick sample would be something like this:
var myArray = ["player_static.png", "player_run0.png", "player_run1.png", "player_run2.png", "player_jump0.png", "player_jump1.png"]
func getSubArray(array:[String],prefix:String) -> [String]
{
var newArray = [String]()
for img in array
{
if img.substringToIndex(img.startIndex.advancedBy(prefix.characters.count)) == prefix
{
newArray.append(img)
}
}
return newArray
}
var test = getSubArray(myArray, prefix: "player_run")

Initialising empty arrays of dictionaries in Swift

I'm trying to wrap my head around initialising empty arrays in Swift.
For an array of strings it's pretty straight forward :
var myStringArray: String[] = []
myStringArray += "a"
myStringArray += "b"
-> ["a", "b"]
and for integers
var myIntArray: Int[] = []
myIntArray += 1
myIntArray += 2
-> [1, 2]
it also works for other types of object such as NSImage objects :
let path = "/Library/Application Support/Apple/iChat Icons/Flags/"
let image1 = NSImage(byReferencingFile: path + "Brazil.png")
let image2 = NSImage(byReferencingFile: path + "Chile.png")
var myImageArray: NSImage[] = []
myImageArray += image1
myImageArray += image2
-> [<NSImage 0x7fe371c199f0 ...>, <NSImage 0x7fe371f39ea0 ...>]
However I can't work out the syntax to initialise an empty array of Dictionaries.
I know you can have an array of Dictionaries because initialising with an initial value works :
let myDict1 = ["someKey":"someValue"]
let myDict2 = ["anotherKey":"anotherValue"]
var myDictArray = [myDict1]
myDictArray += myDict2
-> [["someKey": "someValue"], ["anotherKey": "anotherValue"]]
This however (which you'd expect the syntax to be) fails :
var myNewDictArray: Dictionary[] = []
with the error Cannot convert the expression's type 'Dictionary[]' to type 'Hashable'
So the question is what is the correct way to initialise a empty array of Dictionary Items and why doesn't this syntax var myNewDictArray: Dictionary[] = [] work?
You need to give types to the dictionaries:
var myNewDictArray: [Dictionary<String, Int>] = []
or
var myNewDictArray = [Dictionary<String, Int>]()
Edit: You can also use the shorter syntax:
var myNewDictArray: [[String:Int]] = []
or
var myNewDictArray = [[String:Int]]()
This will create an empty, immutable dictionary:
let dictionary = [ : ]
And if you want a mutable one:
var dictionary = [ : ]
Both of these dictionaries default to Dictionary<String?, AnyObject?>.
The reason this isn't working:
var myNewDictArray: Dictionary[] = []
is that you need to provide types for the keys and values of a dictionary when you define it. Each of these lines will create you an empty array of dictionaries with string keys and string values:
var dictArray1: Dictionary<String, String>[] = Dictionary<String, String>[]()
var dictArray2: Dictionary<String, String>[] = []
var dictArray3 = Dictionary<String, String>[]()
You can no longer use element concatenation.
class Image {}
Image i1
Image i2
var x = [Image]()
x += i1 // will not work (adding an element is ambiguous)
x += [i1] // this will work (concatenate an array to an array with the same elements)
x += [i1, i2] // also good
var yourArrayname = [String]() // String or anyOther according to need
You can use this if u want to use swift 2.3!
let path = "/Library/Application Support/Apple/iChat Icons/Flags/"
let image1 = UIImage(contentsOfFile: readPath + "Brazil.png")
let image2 = UIImage(contentsOfFile: readPath + "Chile.png")
var myImageArray = [UIImage]()
myImageArray.append(image1)
myImageArray.append(image2)

Resources