12
12

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 Extension memo

Last updated at Posted at 2014-06-03

Extension が気になったので、それを試しにやってみてのメモ書き

クラスで試す

クラス作成

class Car {
	var name : String?
	var campany : String = "N/A"

	init (name: String) {
		self.name = name
	}
}

継承

class Beatle : Car {
	init(name: String) {
		super.init(name: name)
		super.campany = "Volkswagen"
	}
}

Extension

extension Car {
	func drive () -> Bool {
		println("\(name) do running.")
		return true;
	}
}

実行

 25> let b = Beatle(name: "My \U+FFF0My \U+FFF0\U+FFEF\U+FFBC")
b: Beatle = {
  lldb_expr_0.Car = {
    name = "My My "
    campany = "Wergen"
  }
}
 26> b.drive
$R1: () -> Bool =
 27> 
 28> b.drive()
My My  do running.
$R2: Bool = true

シェルでは?を書いたら何か壊れた。けど、 Extension して追加したメソッドは、子クラスでも使えた。

Double 型の Extension

型に Extension ができるっぽい。

  1> 
  2> extension Double {
  3.         var byte: Double { return self }
  4.         var kb:  Double { return self * 1_000.0 }
  5.         var kbi: Double { return self * 1_024.0 }
  6.         var mb:  Double { return self * (1_000.0 * 1_000.0) }
  7.         var mbi: Double { return self * (1_024.0 * 1_024.0) }
  8.         var gb:  Double { return self * (1_000.0 * 1_000.0 * 1_000.0) }
  9.         var gbi: Double { return self * (1_024.0 * 1_024.0 * 1_024.0) }
 10. }   
 11> 
 12> ( 1000.mb + 1.gb + 24.mb ) / 1.mb
$R1: Double = 2024

定数でやってたことを、Extension でできるようになった。

感想

  1. わりとさくっと使えるのと、型に Extension ができるようになったのは面白い
  2. extension などでクラスのプロパティには self.name ではなく name だけでいいってのにハマッタ。
12
12
1

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
12
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?