Swift 中变量声明和定义的区别

Difference between variable declaration and definition in Swift

术语 "declaration" 和 "definition" 在 Apple 的 Swift 文档中作为同义词使用,这让我感到困惑。

在 "Initialization" 部分(讨论 class 初始值设定项)下,Apple 声明:

You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.

他们在小节中进一步说明:

You can set the initial value of a stored property from within an initializer, as shown above. Alternatively, specify a default property value as part of the property’s declaration.

我认为变量声明不同于变量定义。

你是对的,这两个意思不同,虽然我认为大多数人只是以相同的意思使用它们,我认为那些 AppleDocs 也是如此。 Here is great article 主题:

总结

A declaration provides basic attributes of a symbol: its type and its name. A definition provides all of the details of that symbol--if it's a function, what it does; if it's a class, what fields and methods it has; if it's a variable, where that variable is stored. Often, the compiler only needs to have a declaration for something in order to compile a file into an object file, expecting that the linker can find the definition from another file. If no source file ever defines a symbol, but it is declared, you will get errors at link time complaining about undefined symbols.

在网上搜索了很多合理的解释后,我似乎找到了答案:

The problem is that the two terms overlap to some extent. Definitions also serve as declarations, because they inject an identifier of a certain type to a scope. However, a declaration isn't a definition because it doesn't entail storage allocation for the declared object. To add to the confusion, the semantics of definitions and declarations is slightly different when applied to types and functions, as I will show momentarily. So let's look at a more detailed analysis of these two terms.

这是文章:Declarations and Definitions

文章给出了进一步的解释和例子。

变量声明意味着告诉编译器它们是特定数据类型的var\funct\struct。变量的定义意味着要求编译器为变量分配内存或为该变量定义存储。您只能定义一个变量一次,但您可以根据需要多次声明它。

我认为 Apple's Swift 4 Language Reference can be construed as the authoritative answer. From the Declarations 部分(强调我的):

A declaration introduces a new name or construct into your program. For example, you use declarations to introduce functions and methods, variables and constants, and to define new, named enumeration, structure, class, and protocol types. You can also use a declaration to extend the behavior of an existing named type and to import symbols into your program that are declared elsewhere.

In Swift, most declarations are also definitions in the sense that they are implemented or initialized at the same time they are declared. That said, because protocols don’t implement their members, most protocol members are declarations only. For convenience and because the distinction isn’t that important in Swift, the term declaration covers both declarations and definitions.