Junior
Is it possible to inherit a structure from multiple parents?
sobes.tech AI
Answer from AI
No. In Objective-C and Swift, structures do not support multiple inheritance.
Swift structures have significant capabilities, including protocols, extensions, methods, computed properties, stored properties, and initializers.
However, to achieve similar goals, Swift uses:
- Protocols: Define a set of requirements (methods, properties, initializers). A type (structure or class) can conform to one or more protocols, thereby acquiring their behavior.
// Protocol example
protocol Animal {
var name: String { get }
func makeSound()
}
// Structure conforming to protocol
struct Dog: Animal {
let name: String
func makeSound() {
print("Woof!")
}
}
- Extensions: Add new functions to existing types without modifying their original code.
// Example extension for String
extension String {
func reversedWords() -> String {
let words = self.split(separator: " ")
return words.reversed().joined(separator: " ")
}
}
// Usage of extension
let sentence = "Hello world"
print(sentence.reversedWords()) // Output: world Hello
Classes in Swift support single inheritance from one parent class but can implement multiple protocols.