Datelà Comparable& Equatable(kể từ Swift 3)
Câu trả lời này bổ sung cho câu trả lời của @Ankit Thakur.
Kể từ Swift 3, Datecấu trúc (dựa trên NSDatelớp bên dưới ) sử dụng các giao thức Comparablevà Equatable.
Comparableđòi hỏi rằng Datethực hiện các nhà khai thác: <, <=, >, >=.
Equatableyêu cầu nhà điều hành Datetriển ==khai.
Equatablecho phép Datesử dụng việc triển khai mặc định của !=toán tử (là nghịch đảo của việc Equatable ==triển khai toán tử).
Đoạn mã mẫu sau đây thực hành các toán tử so sánh này và xác nhận các phép so sánh nào là đúng với các printcâu lệnh.
Chức năng so sánh
import Foundation
func describeComparison(date1: Date, date2: Date) -> String {
var descriptionArray: [String] = []
if date1 < date2 {
descriptionArray.append("date1 < date2")
}
if date1 <= date2 {
descriptionArray.append("date1 <= date2")
}
if date1 > date2 {
descriptionArray.append("date1 > date2")
}
if date1 >= date2 {
descriptionArray.append("date1 >= date2")
}
if date1 == date2 {
descriptionArray.append("date1 == date2")
}
if date1 != date2 {
descriptionArray.append("date1 != date2")
}
return descriptionArray.joined(separator: ", ")
}
Sử dụng mẫu
let now = Date()
describeComparison(date1: now, date2: now.addingTimeInterval(1))
// date1 < date2, date1 <= date2, date1 != date2
describeComparison(date1: now, date2: now.addingTimeInterval(-1))
// date1 > date2, date1 >= date2, date1 != date2
describeComparison(date1: now, date2: now)
// date1 <= date2, date1 >= date2, date1 == date2
let d1 = Date() ; let d2 = Date() ; if d1 > d2 { }làm việc trong tôi Xcode 8 beta 6.