9

它们有何不同?我有点困惑,因为它们似乎是相似的概念。

理解它们对优化编译时间有何帮助?

4

1 回答 1

31

来自 Swift 自己的文档

类型安全

Swift 是一种类型安全的语言。类型安全的语言鼓励你清楚你的代码可以使用的值的类型。如果您的部分代码需要一个字符串,那么您不能错误地将它传递给一个 Int。

var welcomeMessage: String
welcomeMessage = 22 // this would create an error because you  
//already specified that it's going to be a String

类型推断

如果你没有指定你需要的值的类型,Swift 会使用类型推断来计算出合适的类型。类型推断使编译器能够在编译您的代码时自动推断特定表达式的类型,只需检查您提供的值。

var meaningOfLife = 42 // meaningOfLife is inferred to be of type Int
meaningOfLife = 55 // it Works, because 55 is an Int

类型安全和类型推断一起

var meaningOfLife = 42 // 'Type inference' happened here, we didn't specify that this an Int, the compiler itself found out.
meaningOfLife = 55 // it Works, because 55 is an Int
meaningOfLife = "SomeString" // Because of 'Type Safety' ability you will get an 
//error message: 'cannot assign value of type 'String' to type 'Int'' 

具有关联类型的协议的棘手示例:

想象一下以下协议

protocol Identifiable {
    associatedtype ID
    var id: ID { get set }

}

你会像这样采用它:

struct Person: Identifiable {
    typealias ID = String
    var id: String
}

但是,您也可以像这样采用它:

struct Website: Identifiable {
    var id: URL
}

您可以删除typealias. 编译器仍会推断类型。

有关更多信息,请参阅泛型 - 关联类型

由于 Swift 的类型推断,您实际上不需要将 Int 的具体 Item 声明为 IntStack 定义的一部分。因为 IntStack 符合 Container 协议的所有要求,Swift 可以推断出要使用的适当 Item,只需查看 append(_:) 方法的 item 参数的类型和下标的返回类型。事实上,如果你从上面的代码中删除 typealias Item = Int 行,一切仍然有效,因为很清楚应该为 Item 使用什么类型。

类型安全和泛型

假设您有以下代码:

struct Helper<T: Numeric> {
    func adder(_ num1: T, _ num2: T) -> T {
        return num1 + num2
    }
    var num: T
}

T可以是任何数字,例如Int, Double,Int64等。

但是,一旦您键入let h = Helper(num: 10),编译器就会假定它T是一个Int. 它不再接受Double, Int64, 因为它的adder功能。它只会接受Int

这又是因为类型推断和类型安全。

  • 类型推断:因为它必须推断泛型是 type Int
  • 类型安全:因为一旦T设置为 type Int,它将不再接受Int64, Double...

正如您在屏幕截图中看到的,签名现在更改为仅接受类型参数Int 在此处输入图像描述

优化编译器性能的专业提示:

您的代码必须执行的类型推断越少,它的编译速度就越快。因此,建议避免使用集合文字。一个集合的时间越长,它的类型推断就越慢......

不错

let names = ["John", "Ali", "Jane", " Taika"]

好的

let names : [String] = ["John", "Ali", "Jane", " Taika"]

有关更多信息,请参阅此答案

另请参阅为什么 Swift 编译时间这么慢?

该解决方案帮助他的编译时间从 10/15 秒减少到一秒。

于 2016-06-08T15:56:50.090 回答