where do i use extension? [duplicate] - ios

This question already has answers here:
Swift and using class extension
(2 answers)
Closed 6 years ago.
i know that the extension is for to extend types for which you do not have access to the original source code but some developers use extension in a class that themselves make it .
sorry for my english :(
example :
class Category: Mappable {
var PostCategoryId: Int?
var Name: String?
private(set) var Slug: String?
private(set) var PostCategoryParentId: Int?
private(set) var PostCategoryParentPath: String?
var childCategories: [Category]?
var parentCategory: Category?
init() {
}
}
extension Category {
enum CategoryId: Int {
case Comedy = 4
case Action = 6
case Animation = 10
}
}

One use I find can be useful for separating your own logic from methods which must be implemented when conforming to a protocol. Example:
class MyClass {
// My custom logic
}
extension MyClass : SomeProtocol {
// Implement protocol methods here
}
This is purely a code organisation trick but I find it helps to keep things more maintainable.
Another example is for defining default implementations of protocol methods using extensions on protocols. An example:
protocol Askable {
func ask() -> Int
}
extension Askable {
func ask() -> Int {
return 0
}
}
I'm sure there are some other uses developers have come up with so I'm looking forward to some of the other answers here.

Can be useful when a view has a certain set of functionality, with other classes extending that functionality, but also having some other optional functionality that subclasses can choose to use or not (which is the extension)
An example maybe is to have an extension that implements some delegate methods that could be reused in subclasses, maybe a tableview in a uiviewcontroller that subclasses may or may not have, and if the subclass does have the tableview then they can use the extension instead of rewriting the code for the delegate methods (if its always going to be the same code)

Related

Proper way to pass multiple values with protocols in iOS

So I have two ViewControllers. First (MapVC) with map and second (SettingsVC) with many settings that need to be applied to this map.
I thought it would be nice idea to create protocol like
protocol MapSettingsDelegate: class {}
I know that I can specify function inside this protocol. But how I should do it when I have many settings - how should I pass them from SettingsVC to MapVC.
Example:
struct MySettings {
var value1: String
var value2: String
// and so on...
}
protocol MapSettingsDelegate: class {
func settingsUpdated(newSettings: MySettings)
}
and implement it inside your controller
class MapVC : MapSettingsDelegate {
...
func settingsUpdated(newSettings: MySettings) {
// Update everything you need
}
...
}
Feel free to ask for details

Swift: Store Type of implementation of Protocol in static var of protocol extension

Okay so I have this protocol MenuEntry which I want to use to populate a TableView:
protocol MenuEntry {
static var title: String { get }
static func entrySelected(_ menuController: MenuController)
}
I want to implement this protocol in various places and let the item itself decide what to do. It might be a UIViewController which implements the protocol or a simple struct, which then calls a function on the menu itself:
struct SomeEntry: MenuEntry {
static var title: String { return "Some Entry" }
static func entrySelected(_ menuController: MenuController) {
menuController.doSomething()
}
}
Now I want to build the MenuControllers datasource but without actually instantiating the entries because especially my view controllers are not necessarily available when the MenuControllers datasource is populated. Thats why I use static var/func in MenuEntry. Currently, I can simply do this to populate the datasource:
let dataSource: [MenuEntry.Type] = [SomeEntry.self]
And it seems to work pretty well. I can get the entries and call the corresponding functions:
dataSource.first?.title //Gives me "Some Entry"
Now comes the tricky part. I thought I could be really clever and create a protocol extension where I reference all the types in which I implement the protocol like so:
extension MenuEntry {
static var someEntry: MenuEntry.Type { return SomeEntry.self }
//...
}
And then later use them via MenuEntry.someEntry. However, accessing someEntry on MenuEntry gives me an error:
error: static member 'someEntry' cannot be used on protocol metatype 'MenuEntry.Protocol'
So my question is: what am I missing? Am I just trying to misuse the language in a way which is not intended or am I just doing something wrong?
SOLUTION
From the accepted answer below, heres how I now do things. First, we need the mentioned struct (no need for a class I guess):
struct MenuEntries {}
Then, where ever I implement the MenuEntry protocol, I also extend this struct and add the entry like so:
struct SomeEntry: MenuEntry {
static var title: String { return "Some Entry" }
static func entrySelected(_ menuController: MenuController) {
menuController.doSomething()
}
}
extension MenuEntries {
static var someEntry: MenuEntry.Type { return SomeEntry.self }
}
The last thing is to create my datasource like so:
let dataSource: [MenuEntry.Type] = [MenuEntries.someEntry, ...]
Okay, now I have a list of all menu entries in one place. The downside is I have to remember to extend MenuEntries every time. Except there is some magical way to extend a struct on a conditional base I'm not aware of. But I guess thats just over the top and simply not possible.
From The Swift Book
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.”
Your extension is attempting to implement functionality directly in the protocol, but this is not allowed; Only a class, structure or enumeration adopting the protocol can provide functionality.
You could define a class that returns your menu classes:
class MenuFactory {
static var someEntry: MenuEntry.type { return SomeEntry.self }
}

How to use multiple protocols in Swift with same protocol variables?

In swift I'm implementing two protocols, GADCustomEventInterstitial and GADCustomEventBanner.
Both of these protocols require a property called delegate. delegate is a different type in each protocol, and thus a conflict arises.
class ChartBoostAdapter : NSObject, GADCustomEventInterstitial, GADCustomEventBanner, ChartboostDelegate{
var delegate:GADCustomEventInterstitialDelegate?; // Name conflict
var delegate:GADCustomEventBannerDelegate?; // Name conflict
override init(){
}
...
}
They are libraries/frameworks it's not my definition
Then obviously you cannot make the same class adopt both protocols. But you don't really need to. Just separate this functionality into two different classes, as is evidently intended by the designer of these protocols. You are supposed to have one class that adopts GADCustomEventInterstitial and has its delegate, and another class that adopts GADCustomEventBanner and has its delegate. What reason do you have for trying to force these to be one and the same class? As in all things where you are using a framework, don't fight the framework, obey it.
It is actually possible, I just encountered same situation. I had two different but kind of related protocols. In some cases I needed both to be implemented by delegate and in other cases only one and I didn't want to have two properties eg... delegate1, delegate2.
What you need to do is create another combined protocol that inherits from both protocols:
protocol ChartBoostAdapterDelegate: GADCustomEventInterstitialDelegate, GADCustomEventBannerDelegate { }
class ChartBoostAdapter : NSObject, GADCustomEventInterstitial, GADCustomEventBanner, ChartboostDelegate {
weak var delegate: ChartBoostAdapterDelegate?
override init(){
}
...
}
The simple answer is that you can't.
Maybe one protocol depends on another, in which case you would use the dependent protocol for the type of your delegate.
Note that this can be solved using Mixins (possible since Swift 2.0) if you are in a Swift-only environment. It just cannot be solved as long as you need to have the code bridged to Obj-C, as this problem is unsolvable in Obj-C. Yet that can usually be solved by a wrapper class, which I will show later on.
Let's break this down to a minimalist example:
import Foundation
#objc
protocol ProtoA {
var identifier: String { get }
}
#objc
protocol ProtoB {
var identifier: UUID { get }
}
#objc
class ClassA: NSObject, ProtoA, ProtoB {
let identifier = "ID1"
let identifier = UUID()
}
The code above will fail as no two properties can have the same name. If I only declare identifier once and make it a String, compiler will complain that ClassA does not conform to ProtoB and vice verse.
But here is Swift-only code that actually does work:
import Foundation
protocol ProtoA {
var identifier: String { get }
}
protocol ProtoB {
var identifier: UUID { get }
}
class ClassA {
let stringIdentifier = "ID1"
let uuidIdentifier = UUID()
}
extension ProtoA where Self: ClassA {
var identifier: String {
return self.stringIdentifier
}
}
extension ProtoB where Self: ClassA {
var identifier: UUID {
return self.uuidIdentifier
}
}
extension ClassA: ProtoA, ProtoB { }
Of course, you cannot do that:
let test = ClassA()
print(test.identifier)
The compiler will say ambigous use of 'identifier', as it has no idea which identifier you want to access but you can do this:
let test = ClassA()
print((test as ProtoA).identifier)
print((test as ProtoB).identifier)
and the output will be
ID1
C3F7A09B-15C2-4FEE-9AFF-0425DF66B12A
as expected.
Now to expose a ClassA instance to Obj-C, you need to wrap it:
class ClassB: NSObject {
var stringIdentifier: String { return self.wrapped.stringIdentifier }
var uuidIdentifier: UUID { return self.wrapped.uuidIdentifier }
private let wrapped: ClassA
init ( _ wrapped: ClassA )
{
self.wrapped = wrapped
}
}
extension ClassA {
var asObjCObject: ClassB { return ClassB(self) }
}
If you put it directly into the class declaration of ClassA, you could even make it a stored property, that way you don't have to recreate it ever again but that complicates everything as then ClassB may only hold a weak reference to the wrapped object, otherwise you create a retain cycle and neither of both objects will ever be freed. It's better to cache it somewhere in your Obj-C code.
And to solve your issue, one would use a similar wrapper approach by building a master class and this master class hands out two wrapper class, one conforming to GADCustomEventInterstitial and one conforming to GADCustomEventBanner but these would not have any internal state or logic, they both use the master class as storage backend and pass on all requests to this class that implements all required logic.

Override var conforming to a protocol with a var conforming to a child of the overridden var protocol

This is my inheritance structure
Protocols
protocol BaseProtocol {
}
protocol ChildProtocol: BaseProtocol {
}
Classes
class BaseClass: NSObject {
var myVar: BaseProtocol!
}
class ChildClass: BaseClass {
override var myVar: ChildProtocol!
}
I'm receiving a compiler error:
Property 'myVar' with type 'ChildProtocol!' cannot override a property with type 'BaseProtocol!'
What is the best approach to achieve this?
UPDATE
I updated the question trying to implement the solution with generics but it does not work :( This is my code (now the real one, without examples)
Protocols
protocol TPLPileInteractorOutput {
}
protocol TPLAddInteractorOutput: TPLPileInteractorOutput {
func errorReceived(error: String)
}
Classes
class TPLPileInteractor<T: TPLPileInteractorOutput>: NSObject, TPLPileInteractorInput {
var output: T!
}
And my children
class TPLAddInteractor<T: TPLAddInteractorOutput>: TPLPileInteractor<TPLPileInteractorOutput>, TPLAddInteractorInput {
}
Well, inside my TPLAddInteractor I can't access self.output, it throws a compiler error, for example
'TPLPileInteractorOutput' does not have a member named 'errorReceived'
Besides that, when I create the instance of TPLAddInteractor
let addInteractor: TPLAddInteractor<TPLAddInteractorOutput> = TPLAddInteractor()
I receive this other error
Generic parameter 'T' cannot be bound to non-#objc protocol type 'TPLAddInteractorOutput'
Any thoughts?
#tskulbru is correct: it can't be done, and this has nothing to do with your protocols. Consider the example below, which also fails…this time with Cannot override with a stored property 'myVar':
class Foo {
}
class Goo: Foo {
}
class BaseClass: NSObject {
var myVar: Foo!
}
class ChildClass: BaseClass {
override var myVar: Foo!
}
To understand why, let's reexamine the docs:
Overriding Properties
You can override an inherited instance or class property to provide
your own custom getter and setter for that property, or to add
property observers to enable the overriding property to observe when
the underlying property value changes.
The implication is that if you are going to override a property, you must write your own getter/setter, or else you must add property observers. Simply replacing one variable type with another is not allowed.
Now for some rampant speculation: why is this the case? Well, consider on the one hand that Swift is intended to be optimized for speed. Having to do runtime type checks in order to determine whether your var is in fact a Foo or a Bar slows things down. Then consider that the language designers likely have a preference for composition over inheritance. If both of these are true, it's not surprising that you cannot override a property's type.
All that said, if you needed to get an equivalent behavior, #tskulbru's solution looks quite elegant, assuming you can get it to compile. :)
I don't think you can do that with protocols
The way i would solve the problem you are having is with the use of generics. This means that you essentially have the classes like this (Updated to a working example).
Protocols
protocol BaseProtocol {
func didSomething()
}
protocol ChildProtocol: BaseProtocol {
func didSomethingElse()
}
Classes
class BaseClass<T: BaseProtocol> {
var myProtocol: T?
func doCallBack() {
myProtocol?.didSomething()
}
}
class ChildClass<T: ChildProtocol> : BaseClass<T> {
override func doCallBack() {
super.doCallBack()
myProtocol?.didSomethingElse()
}
}
Implementation/Example use
class DoesSomethingClass : ChildProtocol {
func doSomething() {
var s = ChildClass<DoesSomethingClass>()
s.myProtocol = self
s.doCallBack()
}
func didSomething() {
println("doSomething()")
}
func didSomethingElse() {
println("doSomethingElse()")
}
}
let foo = DoesSomethingClass()
foo.doSomething()
Remember, you need a class which actually implements the protocol, and its THAT class you actually define as the generic type to the BaseClass/ChildClass. Since the code expects the type to be a type which conforms to the protocol.
There are two ways you can go with your code, depending what you want to achieve with your code (you didn't tell us).
The simple case: you just want to be able to assign an object that confirms to ChildProtocol to myVar.
Solution: don't override myVar. Just use it in ChildClass. You can do this by design of the language Swift. It is one of the basics of object oriented languages.
Second case: you not only want to enable assigning instances of ChildProtocol, you also want to disable to be able to assign instances of BaseProtocol.
If you want to do this, use the Generics solution, provided here in the answers section.
If you are unsure, the simple case is correct for you.
Gerd

Swift 2.2: Accessing/Modifying Class Variables from Class Protocol

I've been digging around and can't quite seem to find an answer to this... I am trying to implement something like the simplified protocol setup below.
//PROTOCOL SETUP
protocol myProtocol: class {
var thisVariable: CustomType? {get set}
}
extension myProtocol {
func doSomeThings() { //IMPLEMENTATION SPOT 1// }
}
extension theClassIAmUsing: myProtocol {
func doSomeThings() { //IMPLEMENTATION SPOT 2// }
}
//NEW IN SWFIT
extension myProtocol where Self: theClassIAmUsing {
func doSomeThings() { //IMPLEMENTATION SPOT 3// }
}
//CLASS:
class theClassIAmUsing: UIView, myProtocol {
var thisVariable: CustomType? = CustomType() //etc...
//does not implement doSomeThings() but is available
init() {
//some init
}
}
The implementation I am trying to use is performing logic/function based on:
self.thisVariable!.element
and IT WORKS! but only in IMPLEMENTATION SPOTS 2 and 3...
The point of my question is, if I'm subclassing UIView for use around my application, I will need to add an extention of myProtocol "where Self:" is (the next custom class) EVERY TIME I create a new subclass....... (yea this cleans up the class definition code section but seems tedious.)
It may be picky, by wouldn't it seem reasonable to be able to access self.thisVariable in an extention of the protocol so that it may be used in all of my subclassed UIViews??
Am I missing something?
The error I get in IMPLEMENTATION SPOT 1 is:
warning: could not load any Objective-C class information.
This will significantly reduce the quality of type information available.

Resources