How to make Xcode automatically conform to a protocol

左心房为你撑大大i 提交于 2019-11-29 16:50:25

问题


When I use a prototype table view, I always have to conform to the protocol TableViewDataSource. I always forget what methods I need to implement, so I have to look at the source of the protocol every time. This is really time consuming.

I think Xcode must have a feature that automatically implements the needed methods for you, right? Just like IntelliJ IDEA, Eclipse, and Visual Studio.

I want to know where can I find this feature. If there's isn't, is there a workaround for this? At least I don't have to open the source code of the protocol each time I conform to it.

If you don't understand what I mean, here's some code:

I have a protocol

protocol Hello {
    func doStuff ()
}

When I conform to it,

class MyClass: Hello {

}

I often don't remember the names of the methods that I need to implement. If Xcode has a feature that turns the above code, into this:

class MyClass: Hello {
    func doStuff () {
        code
    }
}

Now you understand what I mean? I just want to ask where to find such a feature.


回答1:


Well if i understood your problem then here is a workaround:

try to define methods with protocol as prefix like here hello then you'll not have to remember the methods just start typing protocol name and XCODE will prompt you with all available methods see here:

And if you want autocomplete protocol try Snippets




回答2:


Xcode 9 : you can add missing Protocol Requirements by add new shortcut to your Key Bindings Set

  1. From the top Xcode menu (top left) choose Preferences.
  2. Choose Key Binding.
  3. Search about protocol. you will find Command called Refactor -> Add Missing Protocol Requirements
  4. Press on Key column then add your shortcut. ex: cmd + shift + M

Now you can add missing Protocol Requirements by clicking on class name name (or his extension) then press your shortcut




回答3:


Xcode 9, takes care of implementation of mandatory methods of Swift Datasource & Delegates.

Look at these snapshots, with example of UICollectionViewDataSource:

Indicating warning to implement protocol methods:

By clicking on 'Fix' button, it has added all mandatory methods:




回答4:


Very similar to Amjad's post, Xcode 9/10 brings the functionality to add missing protocol requirements right from within the code editor.

Just "right click" on the class name: "Refactor" --> "Add Missing Protocol Requirements"




回答5:


Xcode won't do it for you.

If you look at the documentation for the protocol, it's clearly marked which functions you have to implement:

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UITableViewDataSource_Protocol/



来源:https://stackoverflow.com/questions/34564253/how-to-make-xcode-automatically-conform-to-a-protocol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!