This question already has answers here:
In Swift, Array [String] slicing return type doesn't seem to be [String]
(6 answers)
Closed 5 years ago.
While try to get sub array With given Range at that time this error.
Cannot subscript a value of type '[Info]' with an index of type 'CountableRange<Int>' .
My code is
Info Modal
class Info : NSObject {
var type : Type = .Unknown
var data = ""
init() {
super.init()
}
}
Array declaration
var currentData : [Info] = []
While trying this code
let moreAnimals: [Info] = self.currentData[0..<5] //above error disply.
let currentData = [Info(), Info(), Info()]
let subarr0 = currentData[0..<2] // ArraySlice<Info>
let subarr1 = Array(currentData[0..<2]) // Array<Info>
to fetch range of element from generics collection we need to convert to NSArray and fetch the element in range using subarrayWithRange Method.
var moreAnimals: [Int] = [1,2,3,4,5,6,7,8,9,10]
var otherarr: [Int] = (moreAnimals as NSArray).subarray(with: NSMakeRange(0, 5)) as! [Int]
output ::
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]
Related
This question already has answers here:
Unique values of array in swift [duplicate]
(4 answers)
Removing duplicate elements from an array in Swift
(49 answers)
Closed 4 years ago.
I have an array which has repeated items, i want to get unique items only so i did this:
let decoded = userDefaults.object(forKey: "shifts") as! Data
myShifts = NSKeyedUnarchiver.unarchiveObject(with: decoded) as! [Shift]
filtered_shifts = myShifts.filter{$0.regionName == region && $0.cityName == city && $0.idService == idservice && $0.quantityStaff != 0}
for shift in filtered_shifts {
let decoded4 = userDefaults.object(forKey: "nationalities") as! Data
let decodedNationalities = NSKeyedUnarchiver.unarchiveObject(with: decoded4) as! [Nationality]
for nationality in decodedNationalities {
if nationality.id == shift.idNationality{
nationalitiesid.append(nationality.id)
nationalities.append(nationality.name)
}
}
}
uniqueNationality = Array(Set(nationalities))
uniqueNationalityid = Array(Set(nationalitiesid))
which is getting me a new array with unique items as i need...
the problem is that the order is diferent when i want the same order ... for exampple:
nationalitiesid = [3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
nationalities = ["Indian", "Indian", "Indian", "Indian", "Indian", "Indian", "Indian", "Indian", "Philippines", "Philippines", "Philippines", "Philippines"]
the unique array is:
uniqueNationality = ["Indian", "Philippines"]
uniqueNationalityid = [4, 3]
and this is wrong since Indian id is 3 and Philippines id is 4!
it should be:
uniqueNationalityid = [3, 4]
How to solve this?
let uniqueList = nationalities.reduce([], {
$0.contains($1) ? $0 : $0 + [$1]
})
This does not directly answer the question. This is an alternative solution. Using a model to group the related information rather keeping two separate arrays in sync.
For more information on Structs and Classes check the documentation
struct Nationality {
var id: Int
var name: String
}
let nationalities = [
Nationality(id: 3, name: "Indian"),
Nationality(id: 4, name: "Philippines")
]
let randomNationalityIds = [3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4]
let nationalitiesResult = Set(randomNationalityIds).flatMap { id in
nationalities.filter({ id == $0.id }).first
}
print(nationalitiesResult)
Output: [__lldb_expr_136.Nationality(id: 4, name: "Philippines"), __lldb_expr_136.Nationality(id: 3, name: "Indian")]
You don't need to keep these in order because the id and name are in the same place.
Instead of creating a non-unique array first and reducing it to a unique array afterwards you could as well collect the nationality strings in a Set of Nationalities:
var nationalitySet = Set<String>()
...
for nationality in decodedNationalities {
nationalitySet.append(nationality)
}
A set won’t store any duplicates so if you add a nationality which is already contained it won’t be added again.
As the set is unordered but converting it into a sorted array is an easy one:
let nationalities = nationalitiesSet.sorted { $0.name < $1.name }
This solution does, however, require Nationality to be hashable, i. e. it must conform to the Hashable protocol:
struct Nationality: Hashable {
var name: String
var id: Int
}
This question already has an answer here:
Swift didSet get index of array
(1 answer)
Closed 5 years ago.
I have an array, with multiple values. I want to detect if one of those values is changed, something like this:
var array =
[
1,
2,
3,
4 { didSet{ print("Value Changed")}},
5,
6
]
Is that possible, in any way?
Thanks
Swift 3.0
You can do like below to Observer which index of array is changed.
var oldArray: [Int] = []
var array = [ 1,2,3,4,5,6] {
willSet {
// Set old array value for compare
oldArray = array
}
didSet {
let changedIndex = zip(array, oldArray).map{$0 != $1}.enumerated().filter{$1}.map{$0.0}
print("index: \(changedIndex)")
}
}
// Now change value of index 4 of array
array[4] = 10 //index: [4]
This question already has answers here:
How can I flatten an array swiftily in Swift?
(4 answers)
Closed 6 years ago.
I have following data:
let array1 = [[1], [2], [3]]
And I want to make it vector:
let result = [1, 2, 3]
Solution off the top of my head:
var result = [Int]()
for arrayOfArray in array1 {
for value in arrayOfArray {
result(value)
}
}
Is there more elegant way to do this ?
You can use flatMap for that.
let array1 = [[1], [2], [3]]
let result = array1.flatMap { $0 }
Output
[1, 2, 3]
Check Apple Documentation on flatMap for more details.
This question already has answers here:
Convert string array description to array
(5 answers)
Closed 6 years ago.
I've that type of String for example:
var test:String = "[1, 0, 4]";
And I need to convert it to an array of Int:
var testConverted:[Int] = [ 1, 0, 4 ];
You'll want to trim off the start and end brackets by using stringByTrimmingCharactersInSet, then get the array of string elements by using componentsSeparatedByString. Then you can finally use flatMap to create an array of integers from this.
For example:
let yourString = "[1, 0, 4]"
// trim off the start and end brackets of the string – then obtain an array of elements by using componentsSeparatedByString
let arrayOfStrings = yourString.stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString: "[]")).componentsSeparatedByString(", ")
// flatMap the arrayOfStrings to an array of integers, filtering out any strings that cannot be represented as numbers
let arrayOfInts = arrayOfStrings.flatMap{Int($0)}
print(arrayOfInts)
Try this:
var test = "[1, 0, 4]"
test = test.substringToIndex(test.endIndex.advancedBy(-1)).substringFromIndex(test.startIndex.advancedBy(1))
var result = test.componentsSeparatedByString(", ").flatMap {Int($0)}
print(result) // [1, 0, 4]
var testarray = NSArray()
testarray = [1,2,2,3,4,5,3]
print(testarray)
testarray.removeObject(2)
I want to remove single object from multiple matching object like
myArray = [1,2,2,3,4,3]
When I remove
myArray.removeObject(2)
then both objects are deleted. I want remove only single object.
I tried to use many extension but no one is working properly. I have already used this link.
Swift 2
Solution when using a simple Swift array:
var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.indexOf(2) {
myArray.removeAtIndex(index)
}
It works because .indexOf only returns the first occurence of the found object, as an Optional (it will be nil if object not found).
It works a bit differently if you're using NSMutableArray:
let nsarr = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = nsarr.indexOfObject(2)
if index < Int.max {
nsarr.removeObjectAtIndex(index)
}
Here .indexOfObject will return Int.max when failing to find an object at this index, so we check for this specific error before removing the object.
Swift 3
The syntax has changed but the idea is the same.
Array:
var myArray = [1, 2, 2, 3, 4, 3]
if let index = myArray.index(of: 2) {
myArray.remove(at: index)
}
myArray // [1, 2, 3, 4, 3]
NSMutableArray:
let myArray = NSMutableArray(array: [1, 2, 2, 3, 4, 3])
let index = myArray.index(of: 2)
if index < Int.max {
myArray.removeObject(at: index)
}
myArray // [1, 2, 3, 4, 3]
In Swift 3 we call index(of:) on both Array and NSMutableArray, but they still behave differently for different collection types, like indexOf and indexOfObject did in Swift 2.
Swift 5: getting index of the first occurrence
if let i = yourArray.firstIndex(of: yourObject) {
yourArray.remove(at: i)
}
If you want to remove all duplicate objects then you can use below code.
var testarray = NSArray()
testarray = [1,2,2,3,4,5,3]
let set = NSSet(array: testarray as [AnyObject])
print(set.allObjects)