如何 return 将 'Date' 类型的值转换为 swift 中的 'String'

How to return convert value of type 'Date' to 'String' in swift

我想在那之后重叠日期 return 布尔值。

func overLap(start1: String, end1: String, start2: String, end2: String) -> Bool {
    if start1 < end2 && start2 < end1 {
        return false
    }
    return true
}

let start1 = "2019/02/01"
let end1 = "2019/02/20"
let start2 = "2019/02/15"
let end2 = "2019/03/02"

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy/MM/dd"

let dateFromString1 = dateFormatter.date(from: start1)
let dateFromString2 = dateFormatter.date(from: end1)
let dateFromString3 = dateFormatter.date(from: start2)
let dateFromString4 = dateFormatter.date(from: end2)

let myString = formatter.String(from: )

let result: Bool = overLap(start1: dateFromString1, end1: dateFromString2, start2: dateFromString3, end2: dateFromString4)
print(result)

这是错误:无法将类型 'Date?' 的值转换为预期的参数类型 'String' 让结果:Bool = overLap(start1: dateFromString1, end1: dateFromString2, start2: dateFromString3, end2: dateFromString4)

overLap方法修改为,

func overLap(start1: Date, end1: Date, start2: Date, end2: Date) -> Bool {
    if start1.compare(end2) == .orderedAscending && start2.compare(end1) == .orderedAscending {
        return false
    }
    return true
}

在上述方法中,参数类型没有使用String,而是使用Date。接下来,使用 compare(_:) 来弥补 start1, end1, start2 and end2 日期。

用法:

let start1 = "2019/02/01"
let end1 = "2019/02/20"
let start2 = "2019/02/15"
let end2 = "2019/03/02"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy/MM/dd"

if let dateFromString1 = dateFormatter.date(from: start1),
    let dateFromString2 = dateFormatter.date(from: end1),
    let dateFromString3 = dateFormatter.date(from: start2),
    let dateFromString4 = dateFormatter.date(from: end2) {
    let result: Bool = overLap(start1: dateFromString1, end1: dateFromString2, start2: dateFromString3, end2: dateFromString4)
    print(result)
}

这是典型的类型不匹配错误。你不能比较苹果 (Date) 和橘子 (String)。

您不需要创建 Date 个实例。将字符串与 numeric 选项

进行比较
func overLap(start1: String, end1: String, start2: String, end2: String) -> Bool {
    if start1.compare(end2, options: .numeric) == .orderedAscending
        && start2.compare(end1, options: .numeric) == .orderedAscending {
        return false
    }
    return true
}

let start1 = "2019/02/01"
let end1 = "2019/02/20"
let start2 = "2019/02/15"
let end2 = "2019/03/02"

let result = overLap(start1: start1, end1: end1, start2: start2, end2: end2)
print(result)