Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Protocol of a particular class

I want to define a variable which of the type UIViewController that conforms to P1.

Question:

  • Should I modify the protocol or the v1 type ?
  • How should I do this ?

Code:

protocol P1 {

    func f1();
}


var v1 : P1 //But needs to be a UIViewController which conforms to `P1`
like image 617
user1046037 Avatar asked Feb 17 '16 09:02

user1046037


People also ask

What is Swift protocol class?

A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocol can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.

How many protocol can a Swift class adopt?

Since classes, structures and, enums can conform to more than one protocol, they can take the default implementation of multiple protocols. This is conceptually similar to multiple inheritance in other languages.

What is difference between protocol and class Swift?

You can create objects from classes, whereas protocols are just type definitions. Try to think of protocols as being abstract definitions, whereas classes and structs are real things you can create.

What is protocol method in Swift?

In Swift, a protocol defines a blueprint of methods or properties that can then be adopted by classes (or any other types). We use the protocol keyword to define a protocol. For example, protocol Greet { // blueprint of a property var name: String { get } // blueprint of a method func message() }


1 Answers

In Swift 4 you can use the new & sign to make a variable that is conforming a protocol AND a class, the syntax is like this:

let vc: UIViewController & P1
like image 191
Jeroen Bakker Avatar answered Sep 23 '22 08:09

Jeroen Bakker