How to extend a protocol in Swift

Protocol inheritance uses the regular inheritance syntax in Swift. protocol Base { func someFunc() } protocol Extended : Base { func anotherFunc() } Swift Protocols do not by default conform to NSObjectProtocol. If you do choose to have your protocol conform to NSObjectProtocol, you will limit your protocol to only being used with classes.

How to implement a network protocol?

Read up on the State design pattern to learn how to avoid lots of switch statements. “sometimes what comes out has some “blind spot”, I mean statuses of the protocol that have not been covered…” State can help avoid gaps. It can’t guarantee a good design, you still have to do that. “…as I have … Read more

Why can’t extensions with protocol conformances have a specific access level?

It’s because it’s impossible to conform to a protocol at any access level other than the access level of the protocol itself. In other words, if you have a public protocol, you cannot have private conformance to it. This is partially because protocol conformance is something that can be queried for at runtime (and therefore … Read more

Swift Declare Class Func in Protocol

You can review Apple’s Documentation (subsection Method Requirements). There says: As with type property requirements, you always prefix type method requirements with the static keyword when they are defined in a protocol. This is true even though type method requirements are prefixed with the class or static keyword when implemented by a class In practice, … Read more

How to require an enum be defined in Swift Protocol

Protocols can have associatedtypes which would just need to be adhered to in any subclass: enum MyEnum: String { case foo case bar } protocol RequiresEnum { associatedtype SomeEnumType: RawRepresentable where SomeEnumType.RawValue: StringProtocol func doSomethingWithEnum(someEnumType: SomeEnumType) } class MyRequiresEnum: RequiresEnum { typealias SomeEnumType = MyEnum func doSomethingWithEnum(someEnumType: SomeEnumType) { switch someEnumType { case .foo: print(“foo”) … Read more

Using as a concrete type conforming to protocol AnyObject is not supported

I ran into the same problem when I tried to implement weak containers. As @plivesey points out in a comment above, this seems to be a bug in Swift 2.2 / Xcode 7.3, but it is expected to work. However, the problem does not occur for some Foundation protocols. For example, this compiles: let container … Read more

What is Protocol Oriented Programming in Swift? What added value does it bring?

Preface: POP and OOP are not mutually exclusive. They’re design paradigms that are greatly related. The primary aspect of POP over OOP is that is prefers composition over inheritance. There are several benefits to this. In large inheritance hierarchies, the ancestor classes tend to contain most of the (generalized) functionality, with the leaf subclasses making … Read more