数组类型推断显示奇怪的编译器错误

时间:2018-11-29 12:42:06

标签: swift type-inference

我遇到这些错误:

  

“字符串”不能转换为“字符串?”

     

“双精度”不能转换为“十进制”

     

“日期?”不能转换为“日期”

在以下示例中

let someArray = [
    SomeBuilder.build(
        someString: "someString",
        someDecimal: 100,
        someDate: Date.make(2018, 8, 20),
        somethingElse: 0
    ),
    SomeBuilder.build(
        someString: "someString",
        someDecimal: 100,
        someDate: Date.make(2018, 8, 20),
        somethingElse: 0
    ),
    SomeBuilder.build(
        someString: "someString",
        someDecimal: 100,
        someDate: Date.make(2018, 8, 20),
        somethingElse: 0
    )
]

struct SomeBuilder {
    static func build(
    someString: String?,
    someDecimal: Decimal,
    someDate: Date,
    somethingElse: Int
    ) -> SomeModel {
        // do something here
        return SomeModel()
    }
}

extension Date {

    static func make(_ year: Int, _ month: Int, _ day: Int) -> Date! {
        let calendar = Calendar(identifier: .gregorian)
        let components = DateComponents(
            calendar: calendar,
            year: year,
            month: month,
            day: day
        )
        return calendar.date(from: components)
    }

}

struct SomeModel {
}

如果将此内容添加到someArray的第四项中(在实际情况下可能是意外事故),您将看到上面的错误之一。

SomeBuilder.build(
    someString: "someString",
    someDecimal: 100,
    someDate: Date.make(2018, 8, 20),
    somethingElsse: 0
)

1 个答案:

答案 0 :(得分:-1)

我们发现类型推断是导致问题的原因,添加数组类型可以帮助编译器找到确切的问题。

解决方案:

let someArray: [SomeModel] = [
    ...
]