我想知道的扩展类和简单的类之间一致的协议(除可读性)什么是扩展的使用符合协议
想我已经创建的类的确切差异具有实现代码如下方法,如
和class DemoVC:UIViewController,UITableViewDelegate,UITableViewDataSource
{
//MARK: -
//MARK: - UITableview delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
...
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
...
}
//Other codes
}
,而不是如果我创建相同的类扩展到符合的tableView方法类似
extension DemoVC:UITableViewDelegate,UITableViewDataSource
{
//MARK: -
//MARK: - UITableview delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return 0
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
....
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
}
}
那么哪个更好,为什么(except READABILITY)
第二个例子 随着双扩展性好
extension Double {
var mm: Double { return self/1_000.0 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
或者
let oneInch = 25.4./1000
所以在这里我想问哪个更好用的双扩展名或者我有简单的分裂加倍1000(如果我需要在特定的类只)为什么?
我相信这是可读性,没有别的。 –
好吧,如果你想在你的扩展中使用类中的'private'属性,你必须将它改为'fileprivate'(只要扩展名在同一个文件中) – Keiwan
@Keiwan I' d要注意的是,你提到的对于Swift 3来说是正确的,在Swift 4中,扩展可以访问私人访问控制,请检查我关于此主题的答案:https://stackoverflow.com/questions/24003918/does-swift-have - 访问修饰符/ 39697920#39697920(“Swift 3和Swift 4访问控制之间有什么区别?”);) –