I'm new to Swift 3 and I have this array of dictionaries in Swift 3:
var arrayPOIsLoaded = [Dictionary<String, Any>]()
And I want to sort it by the Key "name" of the dictionary.
I have look here but nothing seem to work.
I have tried to use predicates but whit no success.
Any help will be appreciated.
Thanks in advance.
Thanks to all.
This is the correct way of writing it:
self.arrayPOIsLoaded.sorted { ($0["name"] as! String) < ($1["name"] as! String) }
You have to add ()
Regards.
Try this
var arrayPOIsLoaded = [Dictionary<String, String>]()
let sortedArray = arrayPOIsLoaded.sorted {$0["name"]! as? String < $1["name"]! as? String}
Related
I want to remove schedule notifications from my app for this I need String array to remove pending notifications I have this type of string its not array this return String from fbdb database but I want array
["01D94B0E-F1AB-421E-9EC3-4A78F0211ED8",
"76E16E51-CB59-4D3F-939E-4D492FFB22BE",
"97696EBD-252F-4A12-962E-995EF306B557",
"84EB98BB-14EB-4D19-83F6-798DCF75E3CD",
"B55621AE-B124-4767-8D6E-C728598E5279"]
I have this is in Array format how can I do this? I know this is beginner question hope u guys will help
let str = """["01D94B0E-F1AB-421E-9EC3-4A78F0211ED8", "76E16E51-CB59-4D3F-939E-4D492FFB22BE", "97696EBD-252F-4A12-962E-995EF306B557", "84EB98BB-14EB-4D19-83F6-798DCF75E3CD", "B55621AE-B124-4767-8D6E-C728598E5279"]"""
let ids = try? JSONSerialization.jsonObject(with: Data(str.utf8)) as? [String] ?? []
you can use default JSONDecoder...
import Foundation
var stringToData: Data? = "[\"01D94B0E-F1AB-421E-9EC3-4A78F0211ED8\", \"76E16E51-CB59-4D3F-939E-4D492FFB22BE\", \"97696EBD-252F-4A12-962E-995EF306B557\", \"84EB98BB-14EB-4D19-83F6-798DCF75E3CD\", \"B55621AE-B124-4767-8D6E-C728598E5279\"]".data(using: .utf8)
let decoded = try JSONDecoder().decode(Array<String>.self, from: stringToData!)
print(decoded)
output:
["01D94B0E-F1AB-421E-9EC3-4A78F0211ED8", "76E16E51-CB59-4D3F-939E-4D492FFB22BE", "97696EBD-252F-4A12-962E-995EF306B557", "84EB98BB-14EB-4D19-83F6-798DCF75E3CD", "B55621AE-B124-4767-8D6E-C728598E5279"]
You can try
let str = """
["1","2","3"]
"""
let res = str.dropFirst(1).dropLast(1)
let arr = res.components(separatedBy: ",").map { $0.replacingOccurrences(of: "\"", with: "") }
I'm trying to cast a dictionary of [String:Bool] to an array of string.
my code is:
var action = [Nourishing:true, Radiance:true]
let actionArray = [action.keys.description] as? [String]
but the result comes out as:
["[\"Nourishing\", \"Radiance\"]"]
How do I fix this?
You should use this directly
let actionArray = Array(action.keys)
I have a Questions
I want to move Value in array to Variable
ex.
[1,2,3] = array
i want to get "1" to Variable
Var = 1 <= Which "1" is Value in array
My code :
//Loop For Seach Value
for result in 0...DataSearch.count-1 {
let Object = DataSearch[result] as! [String:AnyObject];
self.IDMachine_Array.append(Object["IDMac"] as! String!);
self.Password_Array.append(Object["password"] as! String!);
self.Conpassword_Array.append(Object["password_con"] as! String!);
self.Tel_Array.append(Object["Tel"] as! String!);
self.Email_Array.append(Object["Email"] as! String!);
self.Email = String(self.Email_Array);
}
I try Value Email = Email_Array
Result print :
[xxxx#xxxx.com]
but i want Result is :
xxxx#xxxx.com -> without []
Please Help me please.
Thank you.
Sorry if my solution is wrong.
Just get the first element from the array?
self.Email = self.EmailArray.first!
(this is the same as self.Email = self.EmailArray[0])
NB: first! or [0] will both crash if the array is empty. The original question uses as! so obviously just need this to work. However, if you wanted safety you would use something like
if let email as self.EmailArray.first {
self.Email = email
}
or
self.Email = self.EmailArray.first ?? "no email found"
I prepare a swift Array in my Watch Interface and send it to the iOS App:
#IBAction func buttonGeklickt() {
if WCSession.isSupported() {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "hh:mm"
let datumString = dateFormatter.stringFromDate(NSDate())
var swiftArray = [String]()
swiftArray.append(datumString)
var swiftDict = ["a":swiftArray]
session.transferUserInfo(swiftDict)
}
so far so good, on the iOS App the dictionary arrives, but there seems to be something wrong with the Array in the Dictionary:
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
print ("seems to be the same Dict = \(userInfo)")
if let vw = userInfo["a"] as? [String: String] {
print ("Never called! Here I would expect my array from the watch \(vw)")
}
}
I would expect and like vw to hold the same array as swiftArray in the watchApp. However it seems to be of type __NSCFArray:
screenshot
So what I'm doing wrong here?
I'm new to Swift, however I'm experienced with Objective C to solve actually every problem I faced in the past years, but this issue seems to be so basic and it's embarrassing that I'm not able to solve it on my own. So help is much appreciated
If I understand your code correctly, you are saving "a" as value of type [String]. But you are trying to read it as [String:String]. Instead of
if let vw = userInfo["a"] as? [String: String]
try
if let vw = userInfo["a"] as? [String]
I'm using Parse and I have an array of PFObjects called "scorecardData". Each PFObject has a "score" property that is of type Int. I'm trying to sort my array by "score" but I'm getting the following error: "Binary operator '<' cannot be applied to two 'AnyObject?' operands". I'm not sure what I'm doing wrong here. I also tried down casting the objectForKey("score") as! Int but its not letting me do this. Any suggestions? Thanks in advance.
var scorecardData = [PFObject]()
scorecardData.sortInPlace({$0.objectForKey("score") < $1.objectForKey("score")})
You declared scorecardData variable as Array of PFObject. Why are you trying access PFObject property using objectForKey: reserved? Anyway I am not parse expert. But if you declared your array as [PFObject] you can use:
scorecardData.sortInPlace({$0.score < $1.score})
But this won't work unless you subclass PFObject for a more native object-oriented class structure. If you do that remember also to specify:
var scorecardData = [YOUR_NEW_CLASS]()
I strongly recommend subclassing PFObject to make use of all swift type-safe goodies.
But if you want to keep your data structure you can use:
scorecardData.sortInPlace({($0["score"] as! Int) < ($1["score"] as! Int)})
Keep in mind that it's dangerous, and in future avoid it.
If you want to Sort your array of PFOject... You can do this
extension Array where Element:PFObject {
func sort() -> [PFObject] {
return sort { (first, second) -> Bool in
let firstDate = first.objectForKey("time") as! NSDate//objectForKey(Constants.Parse.Fields.User.fullName) as? String
let secondDate = second.objectForKey("time") as! NSDate//objectForKey(Constants.Parse.Fields.User.fullName) as? String
return firstDate.compare(secondDate) == .OrderedAscending
}
}
}
Have you tried doing this?
var query = PFQuery(className:"ScoreCard")
// Sorts the results in ascending order by the score field
query.orderByDescending("score")
query.findObjectsInBackgroundWithBlock {