我在这里有一个数组:
[Type: Optional("web"), Date: Optional("1515970800"),
Type: Optional("web"), Date: Optional("1515193200"),
Type: Optional("web"), Date: Optional("1514847600"),
Type: Optional("web"), Date: Optional("1514674800"),
Type: Optional("twitter"), Date: Optional("1516590000"),
Type: Optional("twitter"), Date: Optional("1516590000")]
这就是数组中的内容:
allData
类型和日期。
如何按Date
过滤allData.sorted(by: { $0.date! < $1.date!})
,以便最高的数字是第一个?
我试过了:
import UIKit
class feedStruct: NSObject {
var type: String?
var date: String?
override init()
{
}
//construct with @name, @address, @latitude, and @longitude parameters
init(type: String, date: String) {
self.type = type
self.date = date
}
//prints object's current state
override var description: String {
return "Type: \(String(describing: type)), Date: \(String(describing: date))"
}
}
但我收到错误:
Any类型的值没有成员日期
这是我的结构:
{{1}}
如何按日期值过滤?
答案 0 :(得分:1)
I suppose you mean
How can I sort
allData
by the Date so the highest number is first
First of all I highly recommend to declare the custom object as struct with non-optional type
and date
and with an initializer which converts the UNIX timestamp to a Date
instance. There is no need to use a class which inherits from NSObject
and there is no need to use optionals.
struct Feed : CustomStringConvertible {
let type: String
let date: Date
init(type : String, date : String) {
self.type = type
self.date = Date(timeIntervalSince1970: TimeInterval(date)!)
}
//prints object's current state
var description: String {
return "Type: \(type), Date: \(date))" // please do not misuse `String(describing:`
}
}
Then declare your allData
array as [Feed]
(never as [Any]
, that's the error reason by the way)
var allData = [Feed]()
Populate the array with Feed
instances
allData = [Feed(type: "web", date: "1515970800"),
Feed(type: "web", date: "1515193200"),
Feed(type: "web", date: "1514674800"),
Feed(type: "web", date: "1516590000"),
Feed(type: "twitter", date: "1516590000"),
Feed(type: "twitter", date: "1515970800")]
and sort it by date descending
allData.sorted{ $0.date > $1.date }
答案 1 :(得分:0)
var allData = ["15101001", "15250151", "11519501", "15192515"]
var convertedArray: [Date] = []
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy"
for dat in testArray {
var date = dateFormatter.date(from: dat)
convertedArray.append(date!)
}
//Method : 1
convertedArray.sort(){$0 < $1}
//Method : 2
convertedArray.sorted(by: {$0.timeIntervalSince1970 <
$1.timeIntervalSince1970})
print(convertedArray)