Say I have the following example:
class ClassOne {
enum Color {
case Red
case Blue
}
func giveColor() -> Color {
return .Red
}
}
class ClassTwo {
let classOne = ClassOne()
var color: Color = classOne.giveColor()
}
The compiler complains that it doesn't know what Color
is in ClassTwo
. How would I best handle this?
Every enum constant is always implicitly public static final. Since it is static, we can access it by using the enum Name. Since it is final, we can't create child enums. We can declare the main() method inside the enum.
In Swift language, we have Structs, Enum and Classes. Struct and Enum are passed by copy but Classes are passed by reference. Only Classes support inheritance, Enum and Struct don't.
Enumerations (or enums for short) in Swift define a common type for a group of related values. According to the Swift documentation, enums enable you to work with those values in a type-safe way within your code. Enums come in particularly handy when you have a lot of different options you want to encode.
In Swift, we can also assign values to each enum case. For example, enum Size : Int { case small = 10 case medium = 12 ... } Here, we have assigned values 29 and 31 to enum cases small and medium respectively.
Your Color
enumeration is a nested type -- you'll access it as ClassOne.Color
. Moreover, you can't assign one property from another in the declaration like that. Leave it unassigned and do it in the init()
:
class ClassOne {
enum Color {
case Red
case Blue
}
func giveColor() -> Color {
return .Red
}
}
class ClassTwo {
let classOne = ClassOne()
var color: ClassOne.Color
init() {
self.color = self.classOne.giveColor()
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With