Swift 고급 문법

Subscript, Extensions, Generic

Subscript

subscript(index: Type) -> Type {
	get {
		// return an appropriate subscript value here
	}set(newValue) {
		// perform a suitable setting action here
	}
}
enum CellMenuType {
    case infoMenu // (0,0)
    case changePW // (0,1)
    case logout // (0,2)
    case memberout // (0,3)
    case non
}

extension SettingTableViewCell {
    subscript (section: Int, row: Int) -> CellMenuType {
        if section == 0 {
            if row == 0 {
                return CellMenuType.infoMenu
            }else if row == 1 {
                return CellMenuType.changePW
            }else if row == 2 {
                return CellMenuType.logout
            }else if row == 3 {
                return CellMenuType.memberout
            }
        }
        return CellMenuType.non
    }
}

// 사용시 아래와 같이 대괄호
let cellMenuType = cell?[indexPath.section, indexPath.row]

Extensions

Generic

Sample Code

Struct Stack using generic

struct Stack<Z> {
    
    private var stackTemp: [Z] = []
    
    mutating func push(_ data: Z) {
        stackTemp.append(data)
    }
    
    mutating func pop() -> Z {
        return stackTemp.removeLast()
    }
    
}

Struct Queue using generic

struct Queue<T> {
    
    private var queArr:[T] = []
    
    mutating func enqueue(_ data: T) {
        queArr.append(data)
    }
    
    mutating func dequeue() {
        queArr.removeFirst()
    }
    
}

func swap using generic

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