swift , sort nsmutableArray with objects [duplicate] - ios

This question already has an answer here:
Sorting an array with instances of a custom class
(1 answer)
Closed 7 years ago.
i have nsmutablearray with objects
user_id , username , user_Last_Update_Info
and i want to sort this array by user_Last_Update_Info
how to do it ??

Try this:
arrayToSort.sortUsingComparator{
(obj1:AnyObject!, obj2:AnyObject!) -> NSComparisonResult in
var dateStr1 = obj1["user_Last_Update_Info"] as NSString
var date1: NSDate = dateFormatter.dateFromString(dateStr1)!
var dateStr2 = obj2["user_Last_Update_Info"] as NSString
var date2: NSDate = dateFormatter.dateFromString(dateStr2)!
return date2.compare(date1)
}

This should help:
// Example for Swift Array
myArray.sortInPlace {
obj1 , obj2 in
dic1.user_Last_Update_Info < dic2.user_Last_Update_Info
}
// Example for Swift NSMutableArray
// newArr is an optional [AnyObject], you should cast it to what you expect
let newArr = myArray.sortedArrayUsingDescriptors([NSSortDescriptor(key: "user_Last_Update_Info", ascending: true)])

Related

Remove certain object from Array of Objects swift [duplicate]

This question already has answers here:
Removing object from array in Swift 3
(13 answers)
Closed 2 years ago.
I have array of objects
let storeArray = [obj1, obj2, obj3]
And I want to remove obj2, how can I remove this with Swift 5?
If you specifically want to remove obj2, you can do this...
var storeArray = [obj1, obj2, obj3]
storeArray.removeAll(where: { $0 == obj2 })
If you know that obj2 is in index 1 of the array and you trust that:
var array = [obj1, obj2, obj3]
guard array.count > 1 else { return }
array.remove(at: 1)
If you want to remove the obj2 without trusting it's index:
var array = [obj1, obj2, obj3]
array.removeAll(where: { $0 == obj2 })
You can try this,
var storeArray = [obj1, obj2, obj3]
storeArray.remove(at: 1)
print(storeArray)

How to filter String array in Swift

By using objective C I have filter year array by using NSPredicate,
Below is code.
yearArray = [yearArray filteredArrayUsingPredicate:[NSPredicate
predicateWithFormat:#"SELF != ''"]];
As per above code it's working fine in objective c , I have to filter array in Swift 3,
What is Input Year Array :-
( Year,"","","",JAN,"","","",FEB,"","","",MAR,"","","",APR,"","","",
MAY,"","","",JUN,"","","",JUL,"","","",AUG,"","","",SEP,"","","",OCT
,"","","", NOV,"","","",DEC,"","","","",WIN,"","","",SPR,"","","",SUM
,"","","",AUT,"","","","",ANN)
Need filter Output Array
(Year,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,WIN,SPR,SUM,AUT,ANN)
Please give solution how to filter array in swift.
Use this code:
let yearArray: [String] = ... // your array of type [String]
let filteredArray = yearArray.filter {
!$0.isEmpty
}
Look at the picture for output:
You can do it by using filter (on an Array type) :
let filteredArray = yearArray.filter{$0 != ""}
It's that simple.
If your array is an NSMutableArray, just cast it to [String] :
if let yearArray = yearArray as? [String] {
let filteredArray = yearArray.filter{$0 != ""}
// add your code here
}

Sort Array of objects according to date

I have an NSMutableArray containing objects and its called HistoryObject, and it has properties date,name,type...etc
i can't find a proper way to sort the array from new to old date for this kind of object.if somebody would explain how can i accomplish that with example !
i have tried the following but its not working:
let sortedArray = HistoryArray.sort({$0.date.compare($1.date) == NSComparisonResult.OrderedAscending })
The date comes in the following format as String : Jun 26, 2016
Do it in this way
// Create your model
class Model {
var date:NSDate!
var name:String!
}
// Not use the NSArray, but use the swift array with sepecific type of data in it
var array = [Model]()
// fake models
for i in 0..<10 {
let model = Model()
model.date = NSDate(timeInterval: Double(i*60), sinceDate: NSDate())
model.name = "\(i)"
array.append(model)
}
// then sort using this code
let newArray = array.sort{ $0.date.timeIntervalSince1970 > $1.date.timeIntervalSince1970 }
You should try it like this,
let sortedArray = HistoryArray.sortInPlace({ $0.date.compare($1.date) == NSComparisonResult.OrderedAscending })
This works fine in Swift2.1
Hope this helps you.

Swift: Convert String to NSMutableArray [duplicate]

This question already has answers here:
Split a String into an array in Swift?
(40 answers)
Closed 6 years ago.
I want to convert following String to NSMuableArray.
var components: String = "library/book/science"
For example, I want to perform the following objective c code in Swift
NSArray *componentsArray = [#"library/book/science" componentsSeparatedByString:#"/"];
NSMutableArray *componentsMutableArray = [[NSMutableArray alloc] initWithArray:componentsArray];
[componentsMutableArray addObject:#"astronomy"];
Here is your working swift code:
var components: String = "library/bool/science"
let componentsArray = components.componentsSeparatedByString("/") //["library", "bool", "science"]
let componentsMutableArray = NSMutableArray(array: componentsArray) //["library", "bool", "science"]
componentsMutableArray.addObject("astronomy") //["library", "bool", "science", "astronomy"]
var components: String = "library/book/science"
var componentMutableArray = components.componentsSeparatedByString("/")
componentMutableArray.append("astronomy")
You need to use NSString in order to call the componentsSeparatedByString function that will split your text into an array based on the separator of your choice.
let theString = NSString(string: "library/book/science")
let components = theString.componentsSeparatedByString("/")

Sort value in dictionary that resides within an array

I have an Array: var messageArray = [AnyObject]() and in that Array there is a single tuple that contains Dictionaries with 10 key/value paires (9 of them not important for the sort): var messageDetailDict = [String: AnyObject]()
Getting and setting those values all work correctly, however now I want to sort the Array by 1 of the values (not keys) of the Dictionary.
Example -> The Array has a tuple containing several Dictionaries:
The key in the Dictionary (which is the first element in the Array) is: 'ReceivedAt' which has a value of 21-03-2015
The key in the Dictionary (which is the second element in the Array) is: 'ReceivedAt' which has a value of 20-03-2015
The key in the Dictionary (which is the third element in the Array) is: 'ReceivedAt' which has a value of 15-03-2015
Now the Array should be sorted so that the values of 'ReceivedAt' will be sorted from earliest date, to the last date.
Hope this makes sense, but it's a bit difficult to explain. Thanks!
EDIT >>>>>
This is the println(messageArray) output:
[(
{
ConversationId = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
Data = "Hello World";
Id = "eeb5ac08-209f-4ef0-894a-72e77f01b80b";
NeedsPush = 0;
ReceivedAt = "/Date(1439920899537)/";
SendAt = "/Date(1436620515000)/";
Status = 0;
},
{
ConversationId = "94cc96b5-d063-41a0-ae03-6d1a868836fb";
Data = "Hello World";
Id = "86b8766d-e4b2-4ef6-9112-ba9193048d9d";
NeedsPush = 0;
ReceivedAt = "/Date(1439921562909)/";
SendAt = "/Date(1436620515000)/";
Status = 0;
}
)]
And the received date is converted to a string with the following method (I do think however this is not important, as it is a time interval, and therefore OK to sort):
func getTimeStampFromAPIValue(dateTimeReceived: String) -> String {
let newStartIndex = advance(dateTimeReceived.startIndex, 6)
let newEndIndex = advance(dateTimeReceived.endIndex, -2)
let substring = dateTimeReceived.substringWithRange(newStartIndex..<newEndIndex) // ell
let receivedAtValueInInteger = (substring as NSString).doubleValue
let receivedAtValueInDate = NSDate(timeIntervalSince1970:receivedAtValueInInteger/1000)
//format date
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yy hh:mm"
var dateString = dateFormatter.stringFromDate(receivedAtValueInDate)
return dateString
}
Since the values of ReceivedAt are timestamps as strings you could apply the following algorithm:
var sortedArray = messageArray.sorted { (dict1, dict2) in
// Get the ReceivedAt value as strings
if let date1String = dict1["ReceivedAt"] as? String,
let date2String = dict2["ReceivedAt"] as? String {
// Compare the date strings to find the earlier of the two
return date1String.compare(date2String) == .OrderedAscending
}
// Couldn't parse the date, make an assumption about the order
return true
}
Try this, change OrderedAscending with OrderedDescending if need in inverse order
messageArray.sortInPlace {
($0["ReceivedAt"] as! NSDate).compare($1["ReceivedAt"] as! NSDate) == .OrderedAscending
}

Resources