Daniel Hall
Daniel Hall

Reputation: 854

Swift function call and protocol

In swift is it possible to declare a method property not as a type but as a protocol?

like:

protocol myProtocol {
    var data1: String {get set}
    var node: Int {get set}
}

class myData: myProtocol {
    var data1: String = "Boo"
    var node: int = 10
}

class myClass {
    func myFunc(data: myProtocol) {
        data.data1 = "Hello"
    }
}

Basically I want to say to the method look I don't care about the type. As long as the object conforms to the protocol its ok

Upvotes: 0

Views: 263

Answers (2)

James P
James P

Reputation: 4836

Yes this is fine, but to modify data you will have to declare a class only protocol.

protocol MyProtocol: AnyObject {
    var data1: String {get set}
    var node: Int {get set}
}

class MyData: MyProtocol {
    var data1: String = "Boo"
    var node: Int = 10
}

class MyClass {
    func myFunc(data: MyProtocol) {
        data.data1 = "Hello"
    }
}

I've also fixed the capitalisation of your classes.

Upvotes: 2

Jay Lee
Jay Lee

Reputation: 1912

You can use associatedtype.

protocol MyProtocol {
  associatedtype CustomData

  var data1: String { get set }
  var node: Int { get set }

  func myFunc(data: CustomData)
}

class MyData: MyProtocol {
  func myFunc(data: String) {
    print(data)
  }

  var data1: String = "Boo"
  var node: Int = 10
}

Also, you should use PascalCase for both protocols and classes, and Int is the integer type for swift.

EDIT: I misunderstood your question. You can also specify a function parameter by an abstract protocol, not just a class or a struct!

protocol MyProtocol {
  var data1: String { get set }
  var node: Int { get set }
}

class MyData: MyProtocol {
  var data1: String = "Boo"
  var node: Int = 10
}

class MyClass {
  func myFunc(data: MyProtocol) {
    print(data.data1)
  }
}

let data = MyData()
let instance = MyClass()
instance.myFunc(data: data)  // Boo

Upvotes: 1

Related Questions