In interesting Idea I had was to use static variables to determine Variadic Generics.
This is what I mean by using C's printf as an example:
func printf(format: static String, _ args: Vargs) {
var string = ""
var iterator = format.makeIterator()
while let char = iterator.next() {
switch char {
case "%":
switch iterator.next() {
case "i"?:
string.append("\(args.pop() staticCastTo Int)")
case "s"?:
string.append(args.pop() staticCastTo String)
default:
fatalError()
}
default:
string.append(char)
}
}
print(string)
}
In this example, if format is known at the call site, then the argument types of Vargs could be determined at the call site by evaluating the branches of the printf function based on the information known at compile time. For this to work, format must be resolved at compile time. This is why format is marked with static.
Some minor points:
- There is already a StaticString type. I could have used this, but I also want to apply the concept to other types such as a static Int, which is an Int that is resolved at compile time.
- The fatalError would be better as a compile time error, as this could be determined at compile time with the static string.
- staticCastTo is a compile time version of as! (the name of staticCastTo should probably be changed)
- Though not necessary in this example, a switch statement that would have staticCastTo cases could be useful. This way of resolving types would not need static variable.