简体   繁体   中英

How do I know how to conform to a specific protocol in Swift?

When I declare a class that I want to conform to a protocol, Swift will show me a message saying that I don't conform to that protocol until all of the protocol's requirements have been met.

Is there a way to get the compiler to give me more specific details about which requirements I'm missing or why I'm not conforming to that protocol or do I always have to open the source code for that protocol with my class's source code side by side and do a manual eye-ball comparison?

To clarify, I'm not asking about any specific protocol in particular, in fact I'm really looking for better support in enforcing my own protocols.

The Issue Navigator (exclamation icon on the left side panel, or CMD+4 ) will reveal which protocols are not being conformed to and why:

在此输入图像描述

Is there a way to get the compiler to give me more specific details about which requirements I'm missing?

Yes, the full compiler output tells you exactly which requirements are missing:

  • Go to the "Report navigator", cmd 8 .
  • Select the last build.
  • For each compiled file there is an icon on the right which opens the full textual output of the compiler.

Simple example:

class A : Equatable {
}

Compiler output:

error: type 'A' does not conform to protocol 'Equatable'
class A : Equatable {
      ^
Swift.Equatable:28:17: note: protocol requires function '==' with type '(A, A) -> Bool'
    public func ==(lhs: Self, rhs: Self) -> Bool

Xcode 9, helps to implement all mandatory methods of Swift Datasource & Delegates.

Here is example of UITableViewDataSource :

Shows warning/hint to implement mandatory methods:

在此输入图像描述

Click on 'Fix' button, it will add all mandatory methods in code:

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM