Make Collection conform to custom protocol - ios

I want to add a generic parameter for all collection type that has isEmpty so they can also have isNotEmpty When I try to make Collection conform to Occupiable I got an compile error
error here : Extension of protocol 'Collection' cannot have an inheritance clause
also String conform to a protocol that inherent from Array so can we just remove extension String: Occupiable { } once we found a solution for the issue above ?
// Anything that can hold a value (strings, arrays, etc)
protocol Occupiable {
var isEmpty: Bool { get }
var isNotEmpty: Bool { get }
}
// Give a default implementation of isNotEmpty, so conformance only requires one implementation
extension Occupiable {
var isNotEmpty: Bool {
return !isEmpty
}
}
extension String: Occupiable { }
// error here : Extension of protocol 'Collection'
// cannot have an inheritance clause
extension Collection: Occupiable { }

You need to set a constraint on conformance.
This will fix the error.
extension Collection where Self: Occupiable { }

Here you have created Occupiable protocol with isEmpty and isNotEmpty variables
so when we implement protocol in any class these two variable need to declare to fullfill protocol. but here you already declare isNotEmpty variable inside Occupiable's extension so now only one isEmpty compulsory in class where we implement protocol.
so isEmpty inside Collection Protocol so we need to extend protocal. but it work in String because string is struct .
you need to code for Collection like:
extension Collection where Self : Occupiable {}

Related

Understanding Swift default valued properties inside a Protocol extension

I have this sample protocol having a default valued property with extension.
protocol SampleProtocol{
var sample:String?{get set}
}
extension SampleProtocol{
var sample:String?{ get { return nil } set{} }
}
Now, my TestClass implements SampleProtocol as below.
class TestClass:SampleProtocol {
var sample: String?{
return "TestClass"
}
}
And there's one helper method that prints a sample value from the SampleProtocol.
func printValue(_ value: SampleProtocol){
print(value.sample)
}
Now the problem is
let testObj = TestClass()
print(testObj.sample) // prints "TestClass"
printValue(testObj) // prints nil
From the above result, I need to understand why when the testObj is typecasted into SampleProtcol, it is considering default implementation from extension instead of the implementation from the TestClass?
The problem is that the TestClass is not implementing the SampleProtocol so when you pass it in the printValue method that takes a SampleProtocol, it will call the default implementation in the protocol extension(since the instance you pass does not implement the protocol method).
In the SampleProtocol you have defined the variable as {get set} but in the TestClass variable you have only provided a getter, this does not match the requirements (If you remove the protocol extension you will see an error that the class does not conform to the protocol).
It will work if you provide a setter:
class TestClass: SampleProtocol {
var sample: String? {
get {
return "TestClass"
} set { }
}
}

Weak' must not be applied to non-class-bound consider adding a protocol conformance that has a class bound [duplicate]

What's the difference between Protocols and class-bound Protocols, and which one we should use in Swift?
protocol A : class { ... }
protocol A { ... }
We get an error when attempting to add a weak delegate when the Protocol is not defined as : class:
protocol A { ... }
weak var delegate: A
Gives the error:
'weak' cannot be applied to non-class type
or
'weak' must not be applied to non-class-bound 'A'; consider adding a protocol conformance that has a class bound
Swift >= 4:
protocol A : AnyObject { ... {
Swift < 4:
protocol A : class { ... }
defines a "class-only protocol": Only class types (and not structures or enumerations) can adopt this protocol.
Weak references are only defined for reference types. Classes
are reference types, structures and enumerations are value types.
(Closures are reference types as well, but closures cannot adopt
a protocol, so they are irrelevant in this context.)
Therefore, if the object conforming to the protocol needs to be stored in a weak property then the protocol must be a class-only protocol.
Here is another example which requires a class-only protocol:
protocol A {
var name : String { get set }
}
func foo(a : A) {
a.name = "bar" // error: cannot assign to property: 'a' is a 'let' constant
}
This does not compile because for instances of structures and enumerations, a.name = "bar" is a mutation of a. If you define
the protocol as
protocol A : class {
var name : String { get set }
}
then the compiler knows that a is an instance of a class type to that
a is a reference to the object storage,
and a.name = "bar" modifies the referenced object, but not a.
So generally, you would define a class-only protocol if you need
the types adopting the protocol to be reference types and not value types.
If you are using Swift 4 or later, use AnyObject:
protocol A : AnyObject { ... }
Using class as before gives the warning and fix-it:
Using 'class' keyword to define a class-constrained protocol is deprecated; use 'AnyObject' instead
Replace 'class' with 'AnyObject'
You can make the protocol derive from any class type like NSObject or AnyObject:
protocol TopNewsTableDelegate : AnyObject {
func topNewsTableDidLoadedStories()
}
Or you can type like this
#objc protocol A { ... }
then you can make a weak delegate reference
protocol CustomProtocolName : NSObjectProtocol {
// ...
}

Protocol Conformance of "Inherited" Property [duplicate]

protocol BasePresenterProtocol : class {}
protocol DashboardPresenterProtocol : BasePresenterProtocol {}
final class DashboardPresenter {
weak var view: DashboardPresenterProtocol?
init() {
self.view = DashboardViewController()
}
func test() {
print("Hello")
}
}
extension DashboardPresenter: DashboardViewProtocol { }
protocol BaseViewProtocol : class {
weak var view: BasePresenterProtocol? { get set }
}
protocol DashboardViewProtocol : BaseViewProtocol {
}
class DashboardViewController {
}
extension DashboardViewController: DashboardPresenterProtocol { }
In the above code, I get an error at following line
extension DashboardPresenter: DashboardViewProtocol { }
that, DashboardPresenter doesn't confirm to protocol DashboardViewProtocol, but I have declared weak var view: DashboardPresenterProtocol? in DashboardPresenter . Although I have declared
Why am I getting this error ? Please let me know what I am doing wrong in this code.
You cannot implement a read-write property requirement of type BasePresenterProtocol? with a property of type DashboardPresenterProtocol?.
Consider what would happen if this were possible, and you upcast an instance of DashboardPresenter to DashboardViewProtocol. You would be able to assign anything that conforms to BasePresenterProtocol to a property of type DashboardPresenterProtocol? – which would be illegal.
For this reason, a read-write property requirement has to be invariant (although it's worth noting that a readable-only property requirement should be able to be covariant – but this currently isn't supported).

Error When Using Protocol as a Type in Swift

I'm using Swift and trying to make some collection objects. These collection objects have a backing Dictionary to hold custom objects. For example, an object might be of type Cat and the collection object would be of type Cats. Cats would have a private dictionary containing values of type Cat. I have other types that also need respective collections (each collection type has specific logic for the type it holds).
I created a protocol to ensure each collection has a few common characteristics. These common functions and subscripts are generally passthroughs to the backing dictionary. Here is the protocol:
protocol ObjectDictionaryProtocol {
// These are necessary for generics to work in protocols
typealias Key: Hashable
typealias Value
// MARK: - Properties
var count: Int { get }
var isEmpty: Bool { get }
var keys: LazyMapCollection<Dictionary<Key, Value>, Key> { get }
var values: LazyMapCollection<Dictionary<Key, Value>, Value> { get }
// MARK: - Subscripts
subscript(key: Key) -> Value? { get set }
}
When I go to actually use the protocol as a type, for instance:
var objects: ObjectDictionaryProtocol
or
init(objs: ObjectDictionaryProtocol) {
...
}
I get the error:
Protocol 'ObjectDictionaryProtocol' can only be used as a generic constraint because it has Self or associated type requirements
I've searched around and it looks like the Hashable protocol I'm conforming to for my Key typealias is causing this. What is the best way to get around this? Is there a way to change the protocol such that I don't need the Hashable, or do I need to do something in the class that is using ObjectDictionaryProtocol? Or maybe there's a better way to effectively 'subclass' a Swift Dictionary (quotes because I realize the Dictionary struct cannot be subclassed)?
A protocol with associated types is less a type and more a template for a type. The actual type exists when the protocol's associated types are specified. Thus ObjectDictionaryProtocol 'becomes' a type when you specify:
ObjectDictionaryProtocol<String,Cat>
but the above is not valid Swift...
So you asked... '[is there] a better way to effectively 'subclass' a Swift Dictionary'. You might get by with an extension with something like:
class Cat {}
extension Dictionary where Value : Cat {
func voice (name: Key) {
if let _ = self[name] {
print ("\(name): Meow")
}
}
}
var someCats = Dictionary<String,Cat>()
someCats["Spot"] = Cat()
someCats.voice("Spot")
// Spot: Meow
Or you may need to actually implement the protocol.
class ObjectDiciontary<Key:Hashable, Value> : ObjectDictionaryProtocol {
var backingDictionary = Dictionary<Key,Value>()
// implement protocol
}
var object : ObjectDictionary<String,Cat> = ...
// ...
The reason is because when you're using typealias you're effectivly making your Protocol into a generic protocol as Protocol<T>. Bear with me here, I'll explain why and how to fix it.
The issue here is that Apple has decided to make typealias the keyword for defining associated types. This is fixed in Swift 2.2 (Xcode 7.3)
You can read more about it on https://github.com/apple/swift-evolution/blob/master/proposals/0011-replace-typealias-associated.md
It's being renamed to associatedtype which makes more sense.
This means your protocol has to be adopted, and there define its associated types.
In your case it would look something like
protocol ObjectDictionaryProtocol {
associatedtype Value
}
extension String : ObjectDictionaryProtocol {
associatedtype = Double
}
The init could look like
init<T : ObjectDictionaryProtocol>(objs: ObjectDictionaryProtocol)
or
init<T : ObjectDictionaryProtocol
where T.Value == Double>(objs: ObjectDictionaryProtocol)
Now for typealias Key: Hashable it means that whatever type that is assigned to Key has to conform or be Hashable
This will give you an error that String isn't conforming to ObjectDictionaryProtocol as it can't fulfil the requirements.
protocol ObjectDictionaryProtocol {
associatedtype Value : FloatingPointType
}
extension String : ObjectDictionaryProtocol {
associatedtype = Int
}
Int isn't a FloatingPointType (but Double is)

Swift - Typealias dictionary with value that implements a generic protocol

I want to typealias a dictionary of String keys and values of objects/structs that implements the Equatable protocol. So I wrote this line of code but it gave me error that I didn't know how to go on to fix.
typealias Storage = [String: Equatable]
I want to use the type [String: Equatable] as a variable in a protocol, e.g:
protocol StorageModel {
var storage: Storage { get set }
init(storage: Storage)
}
Error:
Protocol 'Equatable' can only be used as a generic constraint because
it has Self or associated type requirements
Can anyone suggest a solution?
Generally speaking, the protocol tag isn't required, protocol names are first-class type names and can be used directly:
typealias Storage = [String:Equatable]
In this case, what the error is telling you is that because Equatable includes func == (lhs:Self, rhs:Self) -> Bool and specifically lhs:Self, Equatable can't be used except as a constraint on a generic:
class Generic<T:Equatable> { ... }
Without more details about what you're trying to achieve and how you're trying to use StorageModel, the best I can come up with is:
protocol Matches {
typealias T
func matches(t:T) -> Bool
}
protocol StorageModel {
typealias T
var storage: [String:T] { get set }
init(storage:[String:T])
}
extension Int : Matches {
func matches(target:Int) -> Bool {
return self == target
}
}
class MyClass <T:Matches> {
var model = [String:T]()
}
Another possibility is to use a generic instead of a protocol:
class StorageModel <T:Equatable> {
var storage: [String:T]
init(storage:[String:T]) {
self.storage = storage
}
}
From there you'll need to do some research, dig into the Swift manual, do some googling and see what solves your problem.

Resources