2019년 2월 16일 토요일

Ternary Conditional Operator, Nil-Coalescing Operator




Swift Programming Language Guide: Basic Operators. 코드부분
/* Ternary Conditional Operator */

// The ternary conditonal operator is a special operator with three parts, which takses the form question ? answer 1 : answer2.

if question {
    answer1
} else {
    answer2
}


let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)



let contentHeigth = 40
let hasHeader = true
let rowHeight: Int
if hasHeader {
    rowHeight = contentHeigth + 50
} else {
    rowHeight = contentHeigth + 20
}

/* Nil-Coalescing Operator */

//The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

a != nil ? a! : b

let defaultColorName = "red"
var userDefinedColorName: String?
var colorNameToUse = userDefinedColorName ?? defaultColorName

userDefinedColorName = "green"

colorNameToUse = userDefinedColorName ?? defaultColorName

App, MyMemory

Sample Application for Practice 


MyMemory

(참고: 꼼꼼한 재은씨의 스위프트 실전편, 이재은, 루비페이퍼) 









App, ToDoList

Sample Application for Practice 



ToDoList 

(참고: 야곰의 iOS 프로그래밍, Inflearn) 














2019년 2월 2일 토요일

Subscripts



/* Subscripts */

// Subscript Syntax

subscript(index: Int) -> Int {
   get {
   }
   set(newValue) {
   }
}

struct TimesTable {
   let multiplier: Int
   subscript(index: Int) -> Int {
       return multiplier * index
   }
}

let threeTimesTable = TimesTable(multiplier: 3)
print("six times three is \(threeTimesTable[6])")

// Subscript Usage

var numberOfLegs = ["spider": 8, "ant": 6, "cat": 4]
numberOfLegs["bird"] = 2

// Subscript Options

struct Matrix {
   let rows: Int, columns: Int
   var grid: [Double]
   init(rows: Int, columns: Int) {
       self.rows = rows
       self.columns = columns
       grid = Array(repeating: 0.0, count: rows * columns)
   }
   func indexIsValid(row: Int, column: Int) -> Bool {
       return row >= 0 && row < rows && column >= 0 && column < columns
   }
   
   subscript(row: Int, column: Int) -> Double {
       get {
           assert(indexIsValid(row: row, column: column), "Index ouf of range")
           return grid[(row * columns) + column]
       }
       set {
           assert(indexIsValid(row: row, column: column), "Index out of range")
           grid[(row * columns) + column] = newValue
       }
   }
}

var matrix = Matrix(rows: 2, columns: 2)
matrix[0, 1] = 1.5
matrix[1, 0] = 3.2