在 grammar section Swift 书中有两个语法声明:
explicit-member-expression -> postfix-expression . decimal-digits
explicit-member-expression -> postfix-expression . identifier generic-argument-clause[opt]
第一个用于访问元组:
var tuple = (1, 2, 3)
tuple.1 = tuple.2
第二个用于访问其他成员,例如属性和函数:
struct S {
var property = 0
func function<T>(parameter: T) {}
}
S().property
S().function(3)
但是我找不到可选的generic-argument-clause
的用途。这些成员之后被禁止:
S().property<Int> // error: '>' is not a postfix unary operator
S().function<Int>(3) // error: cannot explicitly specialize a generic function
那么在什么情况下我们可以使用generic-argument-clause
?
最佳答案
模块成员表达式的通用参数子句
有可能 generic-argument-clause
只有模块 ( SomeModule.SomeGeneric<SomeType>()
) 的用例。来自 Language Reference - Expressions :
Explicit Member Expression
An explicit member expression allows access to the members of a named type, a tuple, or a module. It consists of a period (.) between the item and the identifier of its member.
举个例子:
/* Module 'MyLib.a' ... */
class MyClass<T> {
var foo: T?
}
/* ... elsewhere: explicit member expression to module */
MyLib.MyClass<Int>()
奇怪的是,implicit member expressions不包含 generic-argument-clause[opt]
的语法,我们可以将其解释为隐式游标,后者对于显式成员表达式而言,至少不涉及枚举;可能会稍微强化这仅涉及模块的理论。
Grammar Of A Implicit Member Expression
implicit-member-expression → .identifier
模块之外的其他用例?
我不能肯定地说上述内容仅适用于模块,但我无法在成员表达式的上下文中找到通用参数子句的任何其他用途。
下面是一些具有一定讨论性的相关引用摘录;除了模块之外,它也许可以为其他人的研究提供一些值(value)。
首先,什么是通用论证子句?来自 Language Reference - Generic Parameters and Arguments - Generic Argument Clause
A generic argument clause specifies the type arguments of a generic type.
...
The generic argument list is a comma-separated list of type arguments. A type argument is the name of an actual concrete type that replaces a corresponding type parameter in the generic parameter clause of a generic type. The result is a specialized version of that generic type.
...
The specialized version of the generic
Dictionary
type,Dictionary<String, Int>
is formed by replacing the generic parametersKey: Hashable
andValue
with the concrete type argumentsString
andInt
.
现在,同一部分以以下语句结束:
As mentioned in Generic Parameter Clause, you don’t use a generic argument clause to specify the type arguments of a generic function or initializer.
我们跳转到通用参数子句部分并阅读:
... In contrast with generic types, you don’t specify a generic argument clause when you use a generic function or initializer. The type arguments are instead inferred from the type of the arguments passed to the function or initializer.
因此,对于这个问题的主题,我们应该关注成员表达式和(对于 .
的右侧)泛型类型的组合;不是通用函数。但是,除了模块之外,我们还可以在什么情况下将这两个子句和通用参数子句结合起来呢?第一个可能想到的是 enum
具有关联的泛型类型:
enum Bar<T> {
case One(T)
case Two
}
var foo = Bar.One(1)
print(foo.dynamicType) // Bar<Int>
但这是类型推断,而不是泛型参数子句。
从上面来看,我只能将模块视为语法的用例 generic-argument-clause
在成员表达式的上下文中。
关于Swift 语法显式成员表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35386872/