Hi,
I'm currently porting binary file streaming C++ code to Swift, to allow the Swift application to load the C++ generated binary files, and for the life of me I can't find a way to reimplement the C++ ReadField function using Swift genericity :
import Foundation
class MyStream {
func ReadFieldName( _ name: String ) {
}
func ReadFieldValue( _ value: inout Int ) {
}
func ReadFieldValue( _ value: inout Float ) {
}
func ReadField<T>( _ name: String, _ value: inout T ) {
ReadFieldName( name );
ReadFieldValue( &value );
}
}
In despair, I implemented this code snippet in the online playground, and even that generates a compilation error :
/tmp/A3B1A8E7-9DEF-4DDE-BACF-34AAFAD958F4.wbyRFr/main.swift:17:9: error: cannot invoke 'ReadFieldValue' with an argument list of type '(inout T)'
ReadFieldValue( &value );
^
/tmp/A3B1A8E7-9DEF-4DDE-BACF-34AAFAD958F4.wbyRFr/main.swift:17:9: note: overloads for 'ReadFieldValue' exist with these partially matching parameter lists: (inout Float), (inout Int)
ReadFieldValue( &value );
^
I don't see anything fancy here, and this simple design works flawlessly in C++.
The idea is that I implement a few ReadFieldValue functions one by one, and then the generic ReadField function calls the appropriate one depending on the second argument type, this way I can implement the ReadField logic only once.
Any idea why this code can't be compiled ?
For instance, the following code compiles fine :
import Foundation
class MyStream {
func ReadFieldName( _ name: String ) {
}
func ReadFieldValue( _ value: inout Int ) {
}
func ReadFieldValue( _ value: inout Float ) {
}
func ReadField( _ name: String, _ value: inout Int ) {
ReadFieldName( name );
ReadFieldValue( &value );
}
func ReadField( _ name: String, _ value: inout Float ) {
ReadFieldName( name );
ReadFieldValue( &value );
}
}
So after manually instancing the template functions, the code is perfectly valid !
I'm desperately in need of an expert advice here