Learn Swift Fundamentals by preparing for Job Interview, Questions 153 ~ 158 For Protocols
2 min readJul 8, 2022
Swift’s protocol is attractive. Isn’t swift itself called protocol-oriented programming in the first place? When doing unit tests later or writing highly reusable code, the protocol will be a very useful tool.
153) What is Protocol? What kind of methods the protocol contains?
Answer:
- Protocol is a set of Property and Method declarations which are expected to be implemented in the adopting class.
154) Can we define methods in Protocol?
Answer:
- No, protocol just contains method declarations.
protocol AProtocol {
// You can delare property without assigning value
var initialValue: Int { get set }
// You can make read-only property
var getOnly: Int { get }
// You can have function without defining its body
func add()
func subtract()
}struct Calculator: AProtocol { var initialValue: Int
var getOnly: Int func add() { } func subtract() {
}
}
155) Can we extend Protocols?
Answer:
- Yes. To provide default implementations, we can extend protocols.
protocol AProtocol {
// You can delare property without assigning value
var initialValue: Int { get set }
// You can make read-only property
var getOnly: Int { get }
// You can have function without defining its body
func add()
func subtract()
}// Through extension, you can define properties and methods
extension AProtocol {
// You can assign values within extension
var initialValue: Int {
get {
return 0
}
set {
}
}
var getOnly: Int {
get {
return 0
}
} // You can make body within extension
func add() {
print("Add")
}
}struct Calculator: AProtocol { // You must implement subtract() method because it doesn't have body
func subtract() {
}
}
156) How to adopt protocols or how to conform protocol?
Answer:
extension ObjectName: ProtocolName {}
157) How to declare ‘class-only’ adoptable protocol?
Answer:
- By making protocol extend AnyObject.
protocol AProtocol: AnyObject {
var initialValue: Int { get set }
func add()
}// Compile Error
struct Calculator: AProtocol {}
158) How to declare Optional Methods and Properties in Protocols?
Answer:
- Use
- @objc optional var variableName: Int { get set }
- @objc optional func methodName()
- But this protocol is only available to class-type
@objc protocol AProtocol: AnyObject {
@objc optional var variableName: Int { get set }
@objc optional func methodName()
}