I have two arrays.
let array1 = ["Lahari", "Vijayasri"];
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"];
I want to remove the array1 elements in array2 and print the final array-like
result array = ["Ramya", "Keerthi"]
Converting the arrays to Sets and using subtract is a simple and efficient method:
let array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let resultArray = Array(Set(array2).subtracting(Set(array1)))
If maintaining the order of array2 is important then you can use filter with a set -
let compareSet = Set(array1)
let resultArray = array2.filter { !compareSet.contains($0) }
Paulw11 answer works perfectly. But if ordering in array is important you can do this:
let reuslt = array2.filter { !array1.contains($0) }
extension Array where Element: Hashable {
func difference(from other: [Element]) -> [Element] {
let thisSet = Set(self)
let otherSet = Set(other)
return Array(thisSet.subtracting(otherSet))
}
}
var array1 = ["Lahari", "Vijayasri"]
let array2 = ["Lahari", "Vijayasri", "Ramya", "Keerthi"]
let a = array2.difference(from: array1) // ["Ramya", "Keerthi"]
Only take the end.
array2[array1.count...]
I have an array which will always have 4 different autoId's (it grabs 4 at random from a node on firebase) - it is the randomKeyArray shown in the image:
I would like to use the autoIDs from the randomKeyArray to get further information from firebase (users full name and profileImageUrl) set these in separate arrays (names, profileImages and namesWithUrl) so that i can use them later on.
I would like the randomKeyArray[0] to correspond to names[0], profileImages[0], namesWithUrl[0] and the same with 1,2,3 etc.
Right now, the names, profileImages and namesWithUrl arrays are empty and I'm not sure why - would appreciate any help :)
// the arrays are stored outside the viewDidLoad
var randomKeyArray = [String]()
var names = [String]()
var profileImages = [String]()
var namesWithUrl = [String : String]()
//EDIT: this for loop is where i get the random autoId's for the myKeyArray
for _ in 0...3 { //will iterate four times
let count = self.myKeyArray.count //get the number of elements
let randomInt = Int.random(in: 0..<count) //get a random index for the array
let randomUserKey = self.myKeyArray[randomInt]
self.randomKeyArray.append(randomUserKey)
self.myKeyArray.remove(at: randomInt) //remove that object so it's not selected again
}
print(self.myKeyArray)
//for loop is inside a function
for i in 0..<self.randomKeyArray.count {
let thisUserKey = self.randomKeyArray[i]
self.ref.child("users").child(thisUserKey).observeSingleEvent(of: .value, with: { snapshot in
let name = snapshot.childSnapshot(forPath: "fullname").value as! String
let profileImageUrl = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String
self.names.append(name)
self.profileImages.append(profileImageUrl)
self.namesWithUrl[name] = profileImageUrl
//self.currIds.append(self.randomKeyArray)
})
}
Let me know if you need any more info!
EDIT:
I have added the for loop which i get the autoId for the randomKeyArray - I have also tried get the name and profile image when the randomUserKey is called in the first for loop but the arrays still show 0 values
I have a NSMutableArray skippedArray of strings.
skipped Array = ["string1","string2","string3","string4"];
I want to assign the string at index 0 to an UILabel.
I tried lblQuestion.text = skippedArray[j] as! String
but the app crashes at this line.
Can anyone help?
Define NSMutableArray like this:
let skippedArray = ["string1","string2","string3","string4"];
lblQuestion.text = skippedArray.first
or you may also code like this:
let skippedArray : NSMutableArray = ["string1","string2","string3","string4"];
lblQuestion.text = skippedArray.firstObject as! String
There is another way to fetch object of NSMutableArray like this:
let skippedArray : NSMutableArray = ["string1","string2","string3","string4"];
let j = 0;
lblQuestion.text = skippedArray.object(at: j) as! String
Define your variable as Array or simply [String] or just let the definition define it as follows:
var skippedArray: Array<String> = ["string1","string2","string3","string4"]
or
var skippedArray: [String] = ["string1","string2","string3","string4"]
or
var skippedArray = ["string1","string2","string3","string4"]
First, define Mutable Array properly, as mentioned before
var skippedArray = ["string1","string2","string3","string4"]
Second, define your index, your called this "j"
let j = 0
Third, set label text with your string, from string array
lblQuestion.text = skippedArray[j]
if I define array as like this means
var tempArray = [String]()
tempArray = ["Hai", "Hello", "How are you?"]
let indx = tempArray.index(of:"Hai")
there is an option
index(of:)
to find index but if I define like this means
var tempArray = [AnyObject]()
//or
var tempArray = [[String:AnyObject]]()()
there is no option to find index
In Swift.swift you can see this declaration:
extension Collection where Iterator.Element : Equatable {
public func index(of element: Self.Iterator.Element) -> Self.Index?
}
This method is available only for array with Equatable elements; AnyObject doesn't conform to Equatable
EDITED:
you can, though, look for your element like this:
var tempArray = [AnyObject]()
for item in tempArray {
if let typedItem = item as? SomeYourType {
if typedItem == searchItem {
}
}
}
EDITED:
for removing you can use something like this (not tested):
someArr.filter({object in guard let typedObject = (object as? YourType) else {return true}; return typedObject != yourObject })
I'm really confused with regards to how we create an empty array in Swift. Could you please show me the different ways we have to create an empty array with some detail?
Here you go:
var yourArray = [String]()
The above also works for other types and not just strings. It's just an example.
Adding Values to It
I presume you'll eventually want to add a value to it!
yourArray.append("String Value")
Or
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
Add by Inserting
Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):
yourArray.insert("Hey, I'm first!", atIndex: 0)
Or you can use variables to make your insert more flexible:
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
You May Eventually Want to Remove Some Stuff
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)
The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.
Removing Values Without Knowing the Index
But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?
if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}
This should get you started!
There are four ways to create a empty array in Swift 5 and shorthand syntax way is always preferred.
Method 1: Shorthand Syntax
var arr = [Int]()
Method 2: Array Initializer
var arr = Array<Int>()
Method 3: Array with an Array Literal
var arr:[Int] = []
Method 4: Credit goes to #BallpointBen
var arr:Array<Int> = []
var myArr1 = [AnyObject]()
can store any object
var myArr2 = [String]()
can store only string
You could use
var firstNames: [String] = []
There are 2 major ways to create/intialize an array in swift.
var myArray = [Double]()
This would create an array of Doubles.
var myDoubles = [Double](count: 5, repeatedValue: 2.0)
This would create an array of 5 doubles, all initialized with the value of 2.0.
If you want to declare an empty array of string type you can do that in 5 different way:-
var myArray: Array<String> = Array()
var myArray = [String]()
var myArray: [String] = []
var myArray = Array<String>()
var myArray:Array<String> = []
Array of any type :-
var myArray: Array<AnyObject> = Array()
var myArray = [AnyObject]()
var myArray: [AnyObject] = []
var myArray = Array<AnyObject>()
var myArray:Array<AnyObject> = []
Array of Integer type :-
var myArray: Array<Int> = Array()
var myArray = [Int]()
var myArray: [Int] = []
var myArray = Array<Int>()
var myArray:Array<Int> = []
Here are some common tasks in Swift 4 you can use as a reference until you get used to things.
let emptyArray = [String]()
let emptyDouble: [Double] = []
let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0
let arrayMix = [1, "two", 3] as [Any]
var arrayNum = [1, 2, 3]
var array = ["1", "two", "3"]
array[1] = "2"
array.append("4")
array += ["5", "6"]
array.insert("0", at: 0)
array[0] = "Zero"
array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
array.remove(at: 0)
array.removeLast()
array = ["Replaces all indexes with this"]
array.removeAll()
for item in arrayMix {
print(item)
}
for (index, element) in array.enumerated() {
print(index)
print(element)
}
for (index, _) in arrayNum.enumerated().reversed() {
arrayNum.remove(at: index)
}
let words = "these words will be objects in an array".components(separatedBy: " ")
print(words[1])
var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
names.sort() // sorts names in alphabetical order
let nums = [1, 1234, 12, 123, 0, 999]
print(nums.sorted()) // sorts numbers from lowest to highest
Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.
Array can be initialized as :
let emptyArray = [String]()
It shows that its an array of type string
The type of the emptyArray variable is inferred to be [String] from the type of the initializer.
For Creating the array of type string with elements
var groceryList: [String] = ["Eggs", "Milk"]
groceryList has been initialized with two items
The groceryList variable is declared as “an array of string values”, written as [String].
This particular array has specified a value type of String, it is allowed to store String values only.
There are various properities of array like :
- To check if array has elements (If array is empty or not)
isEmpty property( Boolean ) for checking whether the count property is equal to 0:
if groceryList.isEmpty {
print("The groceryList list is empty.")
} else {
print("The groceryList is not empty.")
}
- Appending(adding) elements in array
You can add a new item to the end of an array by calling the array’s append(_:) method:
groceryList.append("Flour")
groceryList now contains 3 items.
Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):
groceryList += ["Baking Powder"]
groceryList now contains 4 items
groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]
groceryList now contains 7 items
As per Swift 5
// An array of 'Int' elements
let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]
// An array of 'String' elements
let streets = ["Albemarle", "Brandywine", "Chesapeake"]
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
you can remove the array content with passing the array index or you can remove all
var array = [String]()
print(array)
array.append("MY NAME")
print(array)
array.removeFirst()
print(array)
array.append("MY NAME")
array.removeLast()
array.append("MY NAME1")
array.append("MY NAME2")
print(array)
array.removeAll()
print(array)
Swift 5
// Create an empty array
var emptyArray = [String]()
// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")
// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)
// Remove elements from an array by index number
emptyArray.remove(at: 2)
// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
emptyArray.remove(at: removeElement)
}
A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)
Initiating an array with a predefined count:
Array(repeating: 0, count: 10)
I often use this for mapping statements where I need a specified number of mock objects. For example,
let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }
Compatible with: Xcode 6.0.1+
You can create an empty array by specifying the Element type of your array in the declaration.
For example:
// Shortened forms are preferred
var emptyDoubles: [Double] = []
// The full type name is also allowed
var emptyFloats: Array<Float> = Array()
Example from the apple developer page (Array):
Hope this helps anyone stumbling onto this page.
Swift 5 version:
let myArray1: [String] = []
let myArray2: [String] = [String]()
let myArray3 = [String]()
let myArray4: Array<String> = Array()
Or more elegant way:
let myElegantArray1: [String] = .init()
extension Array {
static func empty() -> Self {
return []
}
}
let myElegantArray2: [String] = .empty()
The extension above, you can use for any type Array