Prerequisite Information
Hello,
I would like to know if there is some way to create a variable, that could store a few different struct types.
Example:
Code Block struct TestOne { var id: Int var name: String var colour: String static var text: String = "TestOne" } struct TestTwo { var id: Int var lesson: String var description: String static var text: String = "TestTwo" } struct ChosenTest { var test: testOne or testTwo func printText() { print(test.text) } }
I tried adding a protocol,
Code Block protocol TestGroup {}
and then make the structs adhere to it and change it in the ChosenTest, like
Code Block struct TestOne: TestGroup { var id: Int var name: String var colour: String static var text: String = "TestOne" } struct TestTwo: TestGroup { var id: Int var lesson: String var description: String static var text: String = "TestTwo" } struct ChosenTest { var test: TestGroup func printText() { print(test.text) } }
When i try to create a ChosenTest struct and initialize the test variable, it fails because it wants the object of that type and not the actual TestOne.Type or TestTwo.Type
Questions
How could I make the TestOne.Type/TestTwo.Type conform to the ChosenTest protocol?
How could i do something like the code below (or achieve the same result), if the question above is not possible to be done?
Code Block struct ChosenTest { var test: TestGroup func printText() { print(test.text) } }
Something like this?:if I could have a variable inside a struct of type Tor TypeGroup that I could store inside any type of Test struct??
Assuming you have TypeGroup and TypeOne in my last reply.
Code Block struct TestStruct { var testType: TypeGroup.Type = TypeOne.self } func printTest (testStruct: TestStruct) { print(testStruct.testType.desc) } printTest(testStruct: TestStruct()) //->This is a String
: TypeGroup.Type represents that testType can hold any type objects which conforms to TypeGroup, and TypeOne.self is one of the type object conforming TypeGroup.
In Swift, type object is represented by .self after type name.