0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Swift]プロトコル(インターフェース)について

Last updated at Posted at 2021-04-09

Swiftではインターフェースのことをプロトコルというらしい。

最近 TableViewについてソースコードをみていて気になったことがある。

tableView関数って何?これはなんなの?ってところ。
結論から言うと、tableView関数はUITableViewDataSourceで定義されている抽象メソッドだった。
だから、継承先で、関数を定義しないとエラーになる。
https://developer.apple.com/documentation/uikit/uitableviewdatasource
公式ドキュメントより

単純にreturnでInt型の数字を返しているだけだが、これがテーブルのセルの行数に反映される。
おそらく更にどこからかこの関数がよばれて値として戻り値がセットされるのだろう。

ちなみに、オーバーライドは関数の再定義であり、原稿の関数について内容そのものを上書きする。
プロトコルと若干似ているが、役割が違うので見間違えないように。。。

もっと細かく説明すると、

protocol UITableViewDataSource{
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
}
extension ChatListViewController: UITableViewDelegate,UITableViewDataSource{
    
     func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int 

UITableViewDataSourceプロトコルにはこんな感じで
func 関数名(引数) -> 戻り値

と言う感じで関数のみが定義されている。関数自体の中身がないため、それは継承先で
定義しろってこと、

テストコード

import UIKit

protocol SomeProtocol {
    var computedA: String { get }
    func methodA(_ str: String)
    func methodB(a: Int, b: Int) -> Int
}

class someClass {}

extension someClass: SomeProtocol {
    var computedA: String {
        return "a"
    }

    func methodA(_ str: String) {
        print(str)
    }

    <--func methodB(a: Int, b: Int) -> Int {
        return a+b
    } -->ここを消すとエラーになるなぜならプロトコルの抽象クラスに含まれるmethodBを定義していないから
}

let s = someClass()

s.computedA  // a
s.methodA("hello world") // hello world
print(s.methodB(a: 2, b: 5) )// 7
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?