使用 var vs typealias 时有什么区别

what is the difference when using var vs typealias

我使用 typealiasvar(或 let

将我的函数定义为变量
typealias IntFuction = (Int) -> Int

var IntFuction = (Int) -> Int

如果我使用typealias,则完全没有错误。但是,如果我尝试使用 varlet,我会收到如下错误

consecutive statement on a line must be separated by ";"

对于closure,如果可以使用typealiasvar定义为变量应该没问题

谁能解释一下当我使用 var 将函数定义为变量时发生了什么

typealias IntFuction = (Int) -> Int。定义与 (Int) -> Int

相同的类型 IntFuction

var IntFuction = (Int) -> Int 不正确

var IntFuction: (Int) -> Int 声明变量 IntFuction 具有类型:(Int) -> Int

A typealias 是类型或闭包的同义词。

Foundation 框架的一个示例是

typealias NSTimeInterval = Double

声明后 NSTimeInterval 可以代替 Double 在任何地方使用。


你的情况

typealias IntFunction = (Int) -> Int

您可以声明该类型的变量(查看不同的拼写)

var intFunction : IntFunction = { counter in
   return 2 + counter
}

完全相同
var intFunction : (Int) -> Int = { counter in
   return 2 + counter
}

发生错误是因为无法将类型分配 (=) 给变量,编译器需要注释 (:)