ExpressibleByStringLiteral
struct Foo: ExpressibleByStringLiteral {
var raw: String
init(stringLiteral value: String) {
self.raw = value
}
}
现在使用这个可以像这些一样简单
func bar(foo: Foo) {}
let foo1: Foo = "example"
let foo2 = "example" as Foo
bar(foo: "example")
bar(foo: foo1)
bar(foo: foo2)
但这样做是行不通的
let string: String = "example"
bar(foo: string) // Cannot convert value of type 'String' to expected argument type 'Foo'
let foo: Foo = string // Cannot convert value of type 'String' to specified type 'Foo'
bar(foo: string as Foo) // Cannot convert value of type 'String' to type 'Foo' in coercion
// Even string interpolation doesn't work which is weird because it's a string
bar(foo: "\(string)" // Cannot convert value of type 'String' to expected argument type 'Foo'
不
String
也符合
ExpressibleByStringLiteral表达式
ExpressibleBy
类型和这似乎是各地的行为。
这里有什么解决办法吗?