Sobes.tech
Junior — Middle

Is it possible to directly instantiate a protocol object in a programming language?

sobes.tech AI

Answer from AI

In Swift (the programming language for iOS), protocols describe a set of requirements (methods, properties) that a type must implement. You cannot directly create an instance of a protocol because the protocol itself does not contain an implementation.

However, if there is a class or structure that implements the protocol, you can create an instance of that type and work with it through a protocol reference.

Example:

protocol Drawable {
    func draw()
}

class Circle: Drawable {
    func draw() {
        print("Drawing a circle")
    }
}

let shape: Drawable = Circle() // creating an instance of a class that implements the protocol
shape.draw() // calling the protocol method

If you need an object that conforms to the protocol but do not want to create a specific class, you can use wrapper types or anonymous implementations, but direct instantiation of a protocol is not possible.

Is it possible to directly instantiate a protocol… - sobes.tech