Define an object to be `Type` of a Class and to implement a protocol [duplicate] - swift

This question already has answers here:
In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?
(5 answers)
Closed 7 years ago.
I need to define a property of a Class to be of Type UIViewController and to implement protocol MyProtocol. In objective-C I can write something like
UIViewController<MyProtocol> myProperty;
I can't find anything on the documentation and so I suppose that this is not possible :/ can you confirm... here is the example code to add some more info
class SignInPresenter {
var myProperty:UIViewController and MyProtocol <--- here is the problem.

You have two choices. You can either use a Generic with type constraints or use protocol extension with type constraints.
In the case of Generics it looks like:
protocol P1 {
}
class X {
}
class Y : X, P1 {
}
class Z<T: X,P1> {
var myProp : T?
}
In the case of protocol extensions, you can use the protocol to provide the required methods and properties and use the extension to implement them for the specific case when the protocol is implemented by the class (e.g. UIViewController). This may be a better option if you don't really need to require UIViewController, but it will be used in practice. I prefer this kind of design as it allows for looser coupling.

First, multiple protocols are defined with a comma. For example,
class SearchResultsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, APIControllerProtocol
Secondly, variables do not conform to protocols. From Apple's documentation, "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. Any type that satisfies the requirements of a protocol is said to conform to that protocol."

Related

Specify a class that implements a protocol [duplicate]

This question already has answers here:
In Swift, how can I declare a variable of a specific type that conforms to one or more protocols?
(5 answers)
Closed 6 years ago.
Given there are 2 Protocols P1 and P2, it is possible to specify a type that conforms to both protocols, eg:
typealias P = protocol<P1, P2>
Is there a similar way to specify a type that is kind of a class and also conforms to a protocol, e.g. something like this (which does not work):
typealias P = UIView: P1
Unfortunately it's imposible in Swift 2.2 and won't be added in Swift 3.0.
The idea that you want to create Type rule for types that inherit some class and implement protocol.
So it's not very common that you will have such hierarchy and will have property where you want to store one of this classes.
Also in POP paradigm you should have additional protocol that give you properties that you need from UIView.
Maybe you have such usecase:
Then create additional class:
And your type will be P1Base
P.S. That's why if you create #property (nonatomic) UIViewController<UITableViewDelegate> *protocolClassProperty; in Obj-c, it will be bridged as UIViewController! in Swift

Abstract methods in Swift?

I have few questions for Swift developers regarding the concept of abstract classes.
How do you define an abstract class in Swift? Is there any way to prevent a class from being instantiated, while providing an initializer for its subclasses to use?
How do you define abstract methods, while implementing others? When defining abstract methods, Apple generally points you to protocols (interfaces). But they only solve the first part of my question, since all of the methods they define are abstract. What do you do when you want to have both abstract and non-abstract methods in your class?
What about generics? You might have thought about using protocols together with extensions (categories). But then there is an issue with generics because protocols can't have generic types, only typealiases.
I have done my homework and I know about solving these issues using methods, such as fatalError() or preconditionFailure() in the superclass and then overriding them in a base class. But that seems like ugly object design to me.
The reason I'm posting this is to find out whether there exists more general and universal solution.
Thanks in advance,
Petr.
As of today (April 7, 2016), the proposal to introduce abstract classes and methods to Swift (SE-0026) has been deferred.
Joe Groff posted the following in swift-evolution-announce on March 7, 2016:
The proposal has been deferred from Swift 3. Discussion centered around whether abstract classes fit in the direction of Swift as a "protocol-oriented" language. Beyond any religious dogmas, Swift intends to be a pragmatic language that lets users get work done. The fact of the matter today is that one of Swift's primary target platforms is the inheritance-heavy Cocoa framework, and that Swift 2's protocols fall short of abstract classes in several respects [...].
We'd like to revisit this feature once the core goals of Swift 3 have been addressed, so we can more accurately consider its value in the context of a more complete generics implementation, and so we can address the finer points of its design.
I encourage you to read the full email, but I think the conclusion is the same as what you came up with in your question: we're currently stuck with the Objective-C way of doing things (raising exceptions).
There is no Abstract concept in Swift. But we can achieve that scenario by using Inheritance concept like the code below:
class ParentVC:UIViewController {
func loadInformation() {
}
}
class ChildVC:ParentVC {
// This is an Abstract Method
override func loadInformation() {
}
}
How do you define abstract methods, while implementing others?
The "swifty" way of achieving this is combining protocols and extensions, sometimes also typealiases. For data, you are going to define abstract properties in your protocol, then re-define them in a concrete class, then unite all that using a typealias and the & operator:
protocol BaseAbstract: class {
var data: String { get set }
func abstractMethod()
func concreteMethod()
}
extension BaseAbstract {
// Define your concrete methods that use the abstract part of the protocol, e.g.:
func concreteMethod() {
if !data.isEmpty {
abstractMethod()
}
}
}
class BaseImpl {
// This is required since we can't define properties in extensions.
// Therefore, we define a class with a concrete property and then
// unite it with the protocol above in the typealias below.
var data: String = "Hello, concrete!"
}
typealias Base = BaseAbstract & BaseImpl // et voila, `Base` is now ready to be subclassed
class Subclass: Base {
func abstractMethod() { // enforced by the compiler
}
}
(It can get tricker if you have generics in this scenario. Currently trying to figure it out.)

Understanding Swift extension usage in your API design [duplicate]

This question already has an answer here:
Extensions in my own custom class
(1 answer)
Closed 6 years ago.
The Alamofire API has extensions such as extension Request in ResponseSerialization.swift. When designing a Swift API why would you take this approach as opposed to just adding these methods to the Request class (Request.swift)?
I understand the use of extensions to extend API's when you don't control the source. This question is about using them to extend your own API.
For cleanliness or adding functionality to other classes you didn't create (i.e. extension UIColor). You can create separate extensions to add in separate bits of functionality.
For example, if you have a UIViewController and you add a table view to it's view, instead of making the declaration of ViewController look like this:
class ViewController : UIViewController, UITableViewDataSource, UITableViewDelegate
you could separate it all with extensions so you don't clutter your ViewController file.
Like so:
extension ViewController : UITableViewDataSource, UITableViewDelegate
which you could separate from the main body of the ViewController class or extract into a new file.
Extensions are one of the best features of Swift programming language and there are several use cases for them. Once you hold a grip of them you can come up with some really good and understandable code. Some of the use cases are:
1. Extending system types
With Swift you can any system type like Int or String to make some code more readable and to get some more functionality you would otherwise have to write on your own. For example, check out following code that repeats some task a number of times:
extension Int {
func repetitions(task: () -> Void) {
for _ in 0..<self {
task()
}
}
}
Instead of creating separate function for task repetition and managing several parameters you can just extend Int and make it more readable:
3.repetitions({
print("Hello!")
})
// Hello!
// Hello!
// Hello!
Everybody can agree that this is the simplest and cleanest code you can ever create.
2. Make messy code readable
Check the following definition:
class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, CLLocationManagerDelegate {
// a lot of functions
}
If you put everything inside one class or structure, code will get messy at one point and it'll be hard to track which method belongs to which protocol or class. Instead you should be using this:
class MyTableViewController: UIViewController {
}
extension MyTableViewController: UITableViewDelegate {
}
extension MyTableViewController: UITableViewDataSource {
}
// etc...
3. Protocol extensions
Protocol extension are one of the coolest features of Swift. They enable adding methods to any class that adopts the protocol you are extending. For example let's extend CollectionType protocol.
extension CollectionType {
func printAll() {
print(self)
}
}
Now you can use method printAll() on any structure that adopt this protocol! Some of them are native Swift types like Array, Dictionary or Set.
These are just some of the main usages of extensions and they can do a lot more:
Add computed instance properties and computed type properties
Define instance methods and type methods
Provide new initializers
Define subscripts
Define and use new nested types
Make an existing type conform to a protocol

In Swift, what does it mean for protocol to inherit from class keyword?

In Swift, what does it mean for protocol to inherit from class keyword?
e.g.
protocol MyDelegate: class {
}
The gist of Starscream's answer is correct, but it misses the why which I think is important here. It comes down to ARC and memory management.
Swift is a language of reference types and value types. Classes are reference types, while everything else is a value type. Effectively, we're not really specifying that the protocol inherits from class... it's more like we're specifying that the protocol can only be implemented by reference types.
And why is that important?
It's important, because without it, we can't use the weak keyword with the protocol.
protocol ExampleProtocol {}
class DelegatedClass {
weak var delegate: ExampleProtocol?
}
This generates the error:
'weak' cannot be applied to non-class type 'ExampleProtocol'
And why not? Because the weak keyword only makes sense with reference types to which ARC applies. ARC does not apply to value types. And without specifying our protocol with class, we cannot guarantee that our delegate property is set to a reference-type. (And if we don't use weak, we're most likely creating a retain cycle.)
From the Apple docs:
You can limit protocol adoption to class types (and not structures or
enumerations) by adding the class keyword to a protocol’s inheritance
list.
Example:
protocol AProtocol: class {
}
//Following line will produce error: Non-class type 'aStruct' cannot conform to class protocol 'AProtocol'
struct aStruct: AProtocol {
}
The line declaring the structure will spit an error. Following line will produce error:
Non-class type 'aStruct' cannot conform to class protocol 'AProtocol'

Use of a Structure instead of a Class in Swift [duplicate]

This question already has answers here:
Why Choose Struct Over Class?
(17 answers)
Closed 7 years ago.
I learn Swift from some time, I know the differences between structure and class. The main difference is structure is of value type and class is of reference type but didn't understand when to use structure instead of a class. Please explain it.
For example, In case of Protocols:
First, We have just a protocol of struct type:
protocol SomeProtocol{
func doSomeStuff()
}
Second, We make protocol of class type like this:
protocol SomeProtocol: class{
func doSomeStuff()
}
So, Please explain me, when we have to use protocol of struct type or of class type.
Firstly structs are passed by value (copied), and a class is passed by reference (copied just the memory address to the object).You may want to use structs for simpler types, because you get a free init for all the properties your struct has.And with protocols, the first one you can use it on class,struct and enum, the second you say that you only use that on classes,and you may want to put class if your protocol is a delegate or a data source,because you want the property(of the type of your protocol) weak to avoid the memory cycle. IMHO use classes for multi-scene apps because you don't need to take care to update value when you edited something in an another scene.
The protocol is not "of struct type" or "of class type", that is wrong terminology.
If you write SomeProtocol: class you make sure only classes can conform to that protocol, structs cannot. If you don't include the class both classes and structs can conform.
The docs (scroll down to "Class-Only Protocols") tell you that
You can limit protocol adoption to class types (and not structures or enumerations) by adding the class keyword to a protocol’s inheritance list. The class keyword must always appear first in a protocol’s inheritance list, before any inherited protocols.
Use a class-only protocol when the behavior defined by that protocol’s requirements assumes or requires that a conforming type has reference semantics rather than value semantics. For more on reference and value semantics, see Structures and Enumerations Are Value Types and Classes Are Reference Types.