[英]Swift parameter's type not properly inferred?
String
has the following initializers (amongst many): String
具有以下初始化器(在许多中):
init(count: Int, repeatedValue: Character)
init(count: Int, repeatedValue: UnicodeScalar)
so shouldn't the following work? 所以不应该做以下工作?
let str = String(count:8, repeatedValue:"*") // Error: "Extra argument 'count' in call"
Shouldn't the compiler be able to infer the type?! 编译器不应该能够推断出类型吗?! Even if double quotes are strictly for String literals, both
Character
and UnicodeScalar
conform to the UnicodeScalarLiteralConvertible
protocol. 即使双引号是严格的字符串常量,既
Character
和UnicodeScalar
符合UnicodeScalarLiteralConvertible
协议。 So what's happening here? 那么这里发生了什么?
Sure I could always do repeatedValue:("*" as Character)
but then what's the point of having types inferred?! 当然我总是可以做
repeatedValue:("*" as Character)
但是那么推断出类型的重点是什么?!
Well the problem here (as @Thilo already mentioned) is the ambiguity of protocol conformance. 那么这里的问题(正如@Thilo已经提到的)是协议一致性的模糊性。
Character > ExtendedGraphemeClusterLiteralConvertible > UnicodeScalarLiteralConvertible
UnicodeScalar > UnicodeScalarLiteralConvertible
The compiler checks these protocols, but when it hits UnicodeScalarLiteralConvertible
it has no idea which initializer to choose. 编译器检查这些协议,但是当它遇到
UnicodeScalarLiteralConvertible
时,它不知道选择哪个初始化器。
You could make this easier by extending String
with a unique initializer: 通过使用唯一的初始化程序扩展
String
,可以使这更容易:
extension String {
init(count: Int, repeatedCharacter: Character) {
self.init(count: count, repeatedValue: repeatedCharacter)
}
}
let str1 = String(count: 8, repeatedCharacter: "*")
println(str1)
or (although a bit over the top I think) a custom operator which makes it explicit that it's a Character
: 或者(虽然我认为有点超过顶部)一个自定义运算符,它明确表示它是一个
Character
:
postfix operator • {}
postfix func •(c: Character) -> Character { return c }
let str2 = String(count: 8, repeatedValue: "*"•)
println(str2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.