Search code examples
iosswiftprotocols

Calling class properties from within protocol extension


In using protocol extension for default implementation I encounter a problem. I define a protocol with different optional properties and functions to use. In the extension I implement a default function and nil properties. In the implementation I use properties and functions from within the protocol.

On the device it works how I expect. Also on the debugger it gave me the property from the class when I run into breakpoint within the extension implementation.

Can someone help me out why I didn't get the property in the example from the class but the nil property from extension.

Example from playground

import UIKit

protocol Collectable {

    var item: String?  { get }
    func collect()
}

extension Collectable {
    var item: String?  { return nil }
    func collect() {
        if let some = item {
            print("collect \(some)")
        } else {
            print("nothing")
        }
    }
}

class Car: Collectable {
    var item = "letter"
}

let car = Car()
car.collect()

Solution

  • In the protocol your item is optional string, while in your class you declared another variable named also item. Your collect function is looking for the optional item, and in the extension you specified that it should return nil.