Junior — Middle
Kas programmeerimiskeeles saab otse protokolli objekti luua?
sobes.tech AI
Vastus AI-lt
In Swift (programming language for iOS), protocols describe a set of requirements (methods, properties) that a type must implement. It is not possible to directly instantiate a protocol, as 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 reference to the protocol.
Example:
protocol Drawable {
func draw()
}
class Circle: Drawable {
func draw() {
print("Drawing a circle")
}
}
let shape: Drawable = Circle() // create an instance of the class implementing the protocol
shape.draw() // call 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.