스위프트 문법 : Protocols & Generics (영)

김영채 (Kevin)·2021년 1월 13일
0

iOS & Swift

목록 보기
22/107
post-thumbnail

Protocols

  • Holds functions and variables, but it only hold their definitions, not their body.

  • Variables are just the name, type of it. And if it's a get or a set. Not an actual value

    → In a protocol, you won't actually assign a value to a property

  • A class "conforms" to a protocol. If a class conforms to a protocol, it has every variable and functions that were inside the protocol.

protocol CarProto{
	var color: String { get set }
	//any class that conforms to this protocol must be ables=
	//to "get" and "set" the variable color.

	func drive()
	func isAllWheelDrive() -> Bool
	//Defining functions only. Doesn't implement them. Another
	//class will implement the specific functions
}

class Car{

}

//a class can conform to one or more protocols
class BMW: Car, CarProto{

	var color: String = ""
	
	func drive(){
	
	}
	
	func isAllWheelDrive()->Bool{
	
	}	

}

** Delegates and DataSource are naming conventions of a protocol, so don't get confused.

→ Protocols that have the word Delegate at the suffix part, usually deal with user interaction. (i.e what happens when a user taps on a button)

→ Protocols that have the word DataSource at the suffix part, deals with Data. Font size, color, etc

Generics

  • Generic code enables you to write flexible, reusable functions and types that can work with any type, subject to requirements that you define.
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

→ a non-generic function that swaps two values.

→ The problem is, you can only use it for Integer values. If you want to use String values, you would have the write a separate function like the one below:

func swapTwoStrings(_ a: inout String, _ b: inout String) {
    let temporaryA = a
    a = b
    b = temporaryA
}

→ The only different thing about the two functions is the Data type being compared.

** Generic functions, on the other hand, can work with any type.

func swapTwoValues<T>(_ a: inout T, _ b: inout T) {
    let temporaryA = a
    a = b
    b = temporaryA
}

//T becomes the new data type

→ The generic version of the function uses a placeholder type name (called T, in this case) instead of an actual type name (such as Int, String, or Double).

→ In this case, a and b must be of type T, meaning it has to be the same Data type.

  • Because T is a placeholder, Swift doesn’t look for an actual type called T.
profile
맛있는 iOS 프로그래밍

0개의 댓글