10. assert, guard, 프로토콜

LatteQ1·2021년 11월 1일
0

assert

특정 조건을 체크하고, 조건이 성립되지 않으면 메시지를 출력하게 할 수 있는 함수로, 디버깅 모드에서만 동작

var value = 0
assert(value == 0)

value = 2
assert(value == 0, "값이 0이 아닙니다")
// __lldb_expr_527/example.playground:7: Assertion failed: 값이 0이 아닙니다
// Playground execution failed:
// error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION...

guard

무엇인가를 검사하여 그 다음에 오는 코드를 실행할지 말지 결정하는 것으로, guard문에 주어진 조건문이 거짓일 때 else 구문의 내용이 실행되도록 하되, return이나 throw, 혹은 break 구문을 사용하여 이후 코드가 실행되지 않도록 한다.

func guardTest(value: Int) {
	guard value == 0 else { return }
	print("안녕하세요")
}

guardTest(value: 2)
// guard문의 조건(value == 0)을 만족하지 않았으므로 아무것도 출력되지 않고 그냥 return
guardTest(value: 0)
// "안녕하세요"

guard문을 활용한 옵셔널 바인딩

func guardTest(value: Int?) {
	guard let value = value else { return }
	print(value)
}

guardTest(value: 2)
// 2
guardTest(value: nil)
// (guard문의 조건(상수에 대입가능한 값일 것)을 만족하지 않았으므로 아무것도 출력되지 않고 그냥 return

프로토콜

특정 역할을 하기 위한 메서드, 프로퍼티, 기타 요구사항 등의 청사진

protocol SomeProtocol {}
protocol SomeProtocol2 {}

struct SomeStructure: SomeProtocol, SomeProtocol2 {}
class SomeClass: SomeSuperClass, SomeProtocol, SomeProtocol2 {}

프로퍼티 요구사항 준수를 요구하는 방법

요구사항 준수를 이행시킬 프로퍼티에 대해서는 반드시

  • var 키워드에 타입을 명시
  • 특히, 프로퍼티의 타입을 반드시 준수시켜야 할 경우, var 키워드 앞에 static 키워드를 명시
  • 읽기/수정의 가능여부에 맞춰서 getset을 명시

해야 한다.

protocol FirstProtocol {
	var name: Int { get set }
	var age: Int { get }
}

protocol AnotherProtocol {
	static var someTypeProperty: Int { get set }
}

구조체에 프로퍼티와 메서드 이행이 포함된 프로토콜을 제시해보기

protocol FirstProtocol {
	var name: Int { get set }
	var age: Int { get }
}

protocol AnotherProtocol {
	static var someTypeProperty: Int { get set }
}

protocol FullyNames {
	var fullName: String { get set }
	func printFullName()
}

struct Person: FullyNames {
	var fullName: String
	func printFullName() {
		print(fullName)
	}
}

클래스에 초기화 이행이 포함된 프로토콜을 제시해보기

final 키워드를 통해 식별되었다면 모를까, 그렇지 않다면, 일반적으로 클래스에서의 initializer 프로토콜 이행을 위해서는 반드시 required: 키워드가 필요하다.

protocol SomeProtocol3 {
	func someTypeMethod()
}

protocol SomeProtocol4 {
	init(someParameter: Int)
}

protocol SomeProtocol5 {
	init()
}

class SomeClass: SomeProtocol5 {
	required: init() {}
}
profile
전직 시스템엔지니어, 현직 데이터엔지니어, 하지만 하고 싶은건 iOS 개발

0개의 댓글