0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Swift覚書

Last updated at Posted at 2019-08-10

override:
サブクラス側でベースクラスのメソッドやプロパティを実装しなおす(上書きする)こと。
メソッド

class BaseClass {
  func doSomething() {
    // なんかする
  }
}
class SomeClass : BaseClass {
  override func doSomething() {
    super.doSomething()
    // サブクラス側でなんかする
  }
}

プロパティもオーバーライド可能

class BaseClass {
  var something : String
}
class SomeClass : BaseClass {
  var something : String {
    get {
      return super.something
    }
    set {
      let value = newValue ...... // do something ...
      super.something = value
    }
  }
}

delegate

  • デザインパターンのひとつ。
    特徴:
  • 移譲先を意識する必要がない
  • 再利用ができる
  • 複数のclassをまたいで処理を行う
    実装にあたり必要な3つの要素:
    1.プロトコル:任せる処理をメソッドとして定義(delegateメソッド)
protocol ButtonDelegate{
	//おとを鳴らす
	func audio()

	//背景画像を変更する
	func backgroundChange()
}

2.処理を任せるクラス:delegateメソッドを使用し処理の流れを記述

class Button{
	var delegate: ButtonDelegate? = nil
	func click(){
		print("Button is clicked")
		if let dl = self.delegate{
			dl.audio()
			dl.bakgroundChange()
		}else{
			print("donothing")
		}
	}

}

3.処理を任されるクラス:delegateメソッドを実装。処理をここで実装する(overrideと同じ?)

class Button1: ButtonDelegate{
	func audio(){
		print("beep")
	}
	func backgroundChange(){
		print("background is changed")
	}
}

4.実行処理

let button = Button()

let button1 = Button1()
button.delegate = button1
button.click()

didset:

  • 値が更新されたときに呼ばれる
0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?