Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
363 views
in Technique[技术] by (71.8m points)

ios - What is the equivalent for java interfaces or objective c protocols in swift?

I've been looking in to the new Swift language trying to find what's the equivalent for an interface(in java) or a protocol(in objective-c) in Swift, after surfing on the internet and searching in the book provided by Apple, I still can't seem to find it.

Does any one know what's the name of this component in swift and what's its syntax?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Protocols in Swift are very similar to Objc, except you may use them not only on classes, but also on structs and enums.

protocol SomeProtocol {
     var fullName: String { get } // You can require iVars
     class func someTypeMethod() // ...or class methods
}

Conforming to a protocol is a bit different:

class myClass: NSObject, SomeProtocol // Specify protocol(s) after the class type

You can also extend a protocol with a default (overridable) function implementation:

extension SomeProtocol {
      // Provide a default implementation:
      class func someTypeMethod() {
           print("This implementation will be added to objects that adhere to SomeProtocol, at compile time")
           print("...unless the object overrides this default implementation.")
      }
}

Note: default implementations must be added via extension, and not in the protocol definition itself - a protocol is not a concrete object, so it can't actually have method bodies attached. Think of a default implementation as a C-style template; essentially the compiler copies the declaration and pastes it into each object which adheres to the protocol.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...