lolgear
(Dmitry Lobanov)
February 22, 2020, 1:13pm
1
Example:
struct Categories: ExpressibleByStringLiteral {
var category: String = ""
init(category: String) {
self.category = category
}
init(stringLiteral value: String) {
self = .init(category: value)
}
static func abc(_ value: String) -> Categories {
// Error: Cannot convert value String to Categories.
value
}
}
I got error in abc
function.
But, hey, It is not true, I could convert value String to Categories.
Is there any pitch/proposal for this functionality?
UPD :
My misunderstanding of this protocol purpose .
Desired usage would be:
extension Categories {
static let myCategory: Self = "MyCategory"
}
cukr
February 22, 2020, 1:53pm
2
Notice that the protocol is named ExpressibleByStringLiteral
, not ExpressibleByString
Literals are different things than the specific types, check for example this code that uses dictionary literal, but doesn't use a Dictionary
let pairs: KeyValuePairs<Int, String> = [
0: "zero",
0: "nothing",
1: "one",
]
print(pairs) // prints [0: "zero", 0: "nothing", 1: "one"]
It's not a Dictionary
that is converted into KeyValuePairs
because Dictionary
cannot contain repeated keys (0 in this example)
Even though the literal is called "dictionary literal" or "string literal" they aren't Dictionaries or Strings
Swift tries to be a strongly typed language, and a proposal like that would go against that. I don't think it would get much support
3 Likes
Jumhyn
(Frederick Kellison-Linn)
February 22, 2020, 1:55pm
3
ExpressibkeByStringLiteral
is meant to do exactly what the name suggests, that is, allow the type to be initialized from a string literal . It’s not supposed to be an implicit String
conversion protocol, and it’s an explicit design decision of Swift to not allow implicit type conversions. The idiomatic way to express a type conversion is with a single-argument, no-label initializer:
extension Categories {
init(_ string: String) {
self.category = string
}
}
3 Likes
xwu
(Xiaodi Wu)
February 22, 2020, 1:55pm
4
Indeed: not supporting implicit type conversions is explicitly an overarching design principle in Swift.
2 Likes
lolgear
(Dmitry Lobanov)
February 22, 2020, 1:55pm
5
Ah, I see.
Common use case of this protocol would be ( in my example )
extension Categories {
static let someCategory: Self = "myCategory"
}