What’s the difference if I leave a variable in Otocol marked with Static or without Static in Swift 4?

Asked

Viewed 63 times

1

I’m learning about protocols now, and I saw a code snippet in Swift 4 that defines a protocol, follows below the code snippet.

protocol AnotherProtocol {
  static var someTypeProperty: Int { get set }
}

Note that the variable someTypeProperty is stated as static, and in this other case below it appears without the static.

protocol AnotherProcol {
  var someTypeProperty: Int { get set }
}

What is the difference between these two types of protocol implementation in the Swift 4 language?

1 answer

1


The specific question for the protocol seems to indicate already knowing why the static in a regular type, such as a class, for example. The reason is the same, it only differs that the protocol is only the indication of a contract.

A static indicates that the member is the type and not the instance. Used in protocol it indicates that any type that decides to implement this specific protocol in the example AnotherProcol, must have a property called someTypeProperty of the kind Int with the methods accessor and changer. The protocol does not day anything more of how they should be, in the concrete type they can have a code implementation if it is desired, the protocol only requires that it exists the property, does not say how it should proceed, whether it should have some auxiliary field, anything.

  • I didn’t quite understand it... so Static is useless ? Just to indicate that the property has to have get and set ? but this is not indicated right after the var variable:Int {get set} ?

  • Like I said, you know you need to know what the static out of the protocol, you know? If you don’t know it is better to understand it first and then try to understand protocol. When you try to learn things out of order it is harder to learn anything, which is why I always recommend people go down a structured path. Picking up random things never worked.

  • I know what Static is in the concept of c#.. example when you define a method as Static it can be accessed without an instance of the class.

  • Okay, I’ll take it you do, you know what the interface is on C#?

  • Yes, I’ve implemented interfaces in c#

  • So knowing what the static and what is interface of C#, that’s exactly it, only in Swift the interlude she calls the accepted protocol static, as C# 8 will also accept.

  • It is if you are to think, protocols have the same sense of interface... Make requirements of methods and attributes that should be implemented for those who adopt.

  • Exactly what I said in the reply.

  • You iOS program ?

  • I never created anything.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.