preface:
I am using GraphQL, it generates code files for each query you create as a Class file with its own nested types. Its not necessary to know graphQL in this just there for reference. I think this question is a purely Swift code quandary.
I feed that request result into a currently working class as a secondary copy function. The function has a direct type as its argument that I dig out of the generated class file.
The issue is I have to duplicate this copyFrom(type) function for every query it generates since the type it generates is nested within its class.
So I went to trying to change it to type and then typecast it to the Class Single() that the copyFrom function originates from, since I cant access the members any other way that I know of without type casting. While after a bunch of trial and error I get it to build with no warnings but the assigning results are nil
I know from reading Swift does not have a property lookup by string like javascript does object["title"] vs object.title or am I missing some magic function that will make this all work?
tld: I would like to pass a struct into a classes function and assign my classes property from the structs property of the same name
Example GraphQL generated struct
class GeneratedNameAQuery {
public struct Event: GraphQLSelectionSet {
public static let possibleTypes: [String] = ["Event"]
public static var selections: [GraphQLSelection] {
return [
GraphQLField("__typename", type: .nonNull(.scalar(String.self))),
GraphQLField("title", type: .nonNull(.scalar(String.self))),
...
]
}
}
}
Current Data Class
# current copyFrom function that works
# but have to build a duplicate of this routine for every type generated
class Single : Codable, Identifiable {
var title : String?
...
func copyFrom(graphQL: GeneratedNameAQuery.Data.Event){
title = graphQL.title
}
}
Trying to DRY up the code
Updated Class with Any as type for argument
struct MiniTest{
var title : String
}
// data class
class Single : Codable, Identifiable {
var title : String?
...
func copyFrom(graphQL: Any){
title = (graphQL as? Single)?.title // -> nil
// here im trying a simple test with similar logic
var mm = MiniTest(title: "moo")
mm.title = (graphQL as? MiniTest)?.title // -> nil
}
}