CodexBloom - Programming Q&A Platform

Inheritance vs Composition in Swift: Conflicting Property Access Modifiers

👀 Views: 1 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-07
swift oop inheritance composition Swift

I'm following best practices but I'm following best practices but I tried several approaches but none seem to work. Hey everyone, I'm running into an issue that's driving me crazy. I've been working on a Swift project where I've implemented a class hierarchy using inheritance along with some composition to manage shared behavior. My base class `Animal` has a protected property `name`, and I derived a class `Dog` from it. I also have a separate class `Barker` that implements a protocol `Barkable`. My scenario arises when I attempt to access the `name` property from the `Barker` class to generate a bark message. Here's a simplified version of my code: ```swift class Animal { var name: String init(name: String) { self.name = name } } class Dog: Animal { // Dog specific functionality } protocol Barkable { func bark() -> String } class Barker: Barkable { let animal: Animal init(animal: Animal) { self.animal = animal } func bark() -> String { return "Woof! My name is \(animal.name)" } } let myDog = Dog(name: "Buddy") let barker = Barker(animal: myDog) print(barker.bark()) ``` When I run this code, I receive an behavior saying `Value of type 'Animal' has no member 'name'`. I initially thought that since `Dog` inherits from `Animal`, accessing `name` through the `Barker` class should work. I tried changing the access level of `name` to `internal`, but that didn't change anything. Is there a better way to structure this to ensure that I'm able to access the `name` property from the `Barker` class? Am I misunderstanding how access control works in Swift, especially in relation to inheritance and composition? My development environment is macOS. Any feedback is welcome! Has anyone else encountered this? Is there a simpler solution I'm overlooking? The stack includes Swift and several other technologies. Any feedback is welcome!