Search code examples
swiftswiftuiprotocols

Swift creating a Protocol


How do I to represent the following variable found in a data model into a protocol:

The data that it is modelling is JSON and in the format

"imageName": "image1"

The model initialises a image based on the above (imageName)

struct ResultsModel: Codable, Identifiable, Hashable {

    var id: Int
    var name: String
    var imageName: String
    var image: Image {
            Image(imageName)
        }
}
protocol Attachment {

    var id: Int { get set }
    var name: String { get set }
    var imageName: String { get set }

    var image : Image {
            Image(imageName)
        }
}

I get the error "Expected get or set in a protocol property" but where do I add this? Or how do I write a protocol that initialises a Image by String?

Ive tried added get set to

var image: Image {
        Image(imageName) 
} {get set}

var image: Image {get set} {
        Image(imageName) 
} 

but both return with "Expected get or set in a protocol property"


Solution

  • Swift protocols cannot define properties with default implementations, but you can do it with a protocol extension. See below:

    protocol Attachment {
        var id: Int { get set }
        var name: String { get set }
        var imageName: String { get set }
    
        var image : Image { get }
    }
    
    extension Attachment {
        var image: Image {
            return Image(self.imageName)
        }
    }