swift 문법 총정리(11) Extension & Protocol

Updated:

Extension

기존에 있던 클래스나 struct에 추가적인 기능을 하고싶을 때 사용한다. 전반적으로 추가하고 싶은 기능이 있을 때 사용하면 좋다. extension은 가장 바깥쪽에 정의. class같은거 안에 들어갈 수 없고 어디서든 접근이 가능하다.

//색깔 지정
//메인컬러 - 
//서브컬러 - 
//텍스트 메인 타이틀 -
//텍스트 상세 -  
extension String {
}
//자기 이름이 있는게 아니라 기능을 추가하고 싶은 대상만 존재

var titleColor: UIColor!
var descriptionColor: UIColor!

titleColor = UIColor(red: 240/256, green: 30/255, blue: 30/255, alpha: 1)
descriptionColor = UIColor(red: 50/255, green: 250/255, blue: 30/255, alpha: 1)

var subTitleColor: UIColor
subTitleColor = UIColor(red: 20/255, green: 250/255, blue: 30/255, alpha: 1)

extension UIColor{
        //var myName = "jin"
        //extension안에 저장 프로퍼티를 사용할 수 없다.
	var mainRedColor: UIColor {
		return UIColor(red: 50/255, green: 250/255, blue: 30/255, alpha: 1)
	}
	var subGreenColor: UIColor{
		return UIColor(red: 50/255, green: 250/255, blue: 30/255, alpha: 1)
	}}
}

titleColor = UIColor().mainRedColor
descriptionColor = UIColor().subGreenColor

Protocols

프로토콜은 사용하기 위해서 반드시 구현해야 하는 것들은 구현해야지 사용할 수 있다. protocol은 특정 작업 혹은 기능들을 구현하기 위한 메소드, 프로퍼티 그리고 기타 다른 요구사항들의 청사진이다.

class MyClass: UIViewController, UITableViewDataSource{
	//UITableViewDataSource protocol을 사용하기 위해 반드시 사용해야하는 func
	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) ->
		Int {
			return 5
	}

	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
		UITableViewCell {
			return UITableViewCell()
		}
}

protocol DeskMaterial {
	var top: String { get set }
	var middle: String { get set }
}
protocol DeskSize{
	var width: Int { get set }
	var height: Int { get set }
	//규격만 지정
	func area() -> Int 
}


class MyClass: DeskSize, DeskMaterial{
	var top: String = ""
	
	var middle: String = ""

	var width: Int

	var height: Int = 0

	func area() -> Int {
		return width * height
	}
}

var myClass = MyClass()
myClass.width = 20
myClass.height = 30
myClass.area()
//600

Reference

인프런 강의

Tags: ,

Categories:

Updated:

Leave a comment