0%

191120-swift-basic1

Type Annotation & Type Inference & Literals

Type Annotation

  • 변수 선언 시 타입을 명확하게 지정하는 것
1
2
3
4
5
6
7
8
9
let year: Int = 2019

let language: String
language = "Swift"

var red, green, blue: Double
red = 255.0
green = 150.123
blue = 75

Type Inference

  • 변수 선언 시 값을 통해 변수의 타입을 추론하는 것
1
2
3
4
5
6
7
8
9
10
11
let name: String = "Babo"
type(of: name) // String.type

let age: Int = 7
type(of: age) // Int.type

var weight = 48.3
type(of: weight) // Double.type

var isDog = true
type(of: isDog) // Bool.type

Literals & Types

  • 리터럴: 고정된 값으로 표현되는 문자 그 자체
  • 정수 / 실수 / 문자 / 문자열 / 불리언 리터럴 등

Operator

Ternary Operator 삼항연산자

  • 결과: ? 앞의 식이 참일때 True : False
1
2
3
4
5
6
7
a > 0 ? "positive" : "zero or negative"

if a > 0 { // 삼항연산자와 동일하게 동작
"positive"
} else {
"negative"
}

Assignment Operators 할당연산자

1
2
3
4
5
6
7
8
9
10
11
12
value += 1
//value = value + 1 위와같은
value -= 5
//value = value - 5
value *= 2
//value = value * 2
value /= 2
//value = value / 2
value %= 2
//value = value % 2 //나머지가 나옴

// 미지원 : value++, value--

Arithmetic Operators 산술 연산자

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 실수에서의 나눗셈
let e = 123.4
let f = 5.678

e / f // 단순히나누면 나머지가 틀림: 21.73300457907714

// 실수로 나머지를 구할때 사용
// 나머지 구하기 (내림)
e.truncatingRemainder(dividingBy: f) // 4.162000000000007

// 나머지 구하기 계산 방법
let quotient = (e / f).rounded(.towardZero) // 몫: 21
let remainder = e.truncatingRemainder(dividingBy: f) //나머지: 4.162000000000007
let sum = f * quotient + remainder // 123.4
5.678 * 21 // 119.238
5.678 * 21 + 4.162000000000007 // 123.4

Question

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// 범위 연산의 순서를 반대로(내림차순) 적용하려면?

// 반대 reversed
for index in (1...5).reversed() {
print("\(index) times 5 is \(index * 5)")
}

//결화
5 times 5 is 25
4 times 5 is 20
3 times 5 is 15
2 times 5 is 10
1 times 5 is 5

// 10~1까지 -1로
for index in stride(from: 10, through: 1, by: -2) {
print("\(index) times 5 is \(index * 5)")
}

//결과
10 times 5 is 50
8 times 5 is 40
6 times 5 is 30
4 times 5 is 20
2 times 5 is 10

Function

  • Input 과 Output 이 모두 있는 것 (Function)

  • Input 이 없고 Output 만 있는 것 (Generator)

  • Input 이 있고 Output 은 없는 것 (Consumer)

  • Input 과 Output 이 모두 없는 것

1
2
3
4
// 기본유형
func <함수이름> (<parameterName>: <Type>) -> <ReturnType> {
<statements>
}

Input이 없는 경우

1
2
3
4
5
6
7
8
func hello1() {
print("Hello, world!")
}

//
func hello2() -> String {
return "Hello, world!"
}

Output이 없는 경우

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
func say(number: Int) {
print(number)
}
// void는 반환값이 없음 ()대체하거나 생략가능
func say(word: String) -> Void {
print(word)
}

func say(something: String) -> () {
print(something)
}

// 3개는 같음
say(number: 1)
say(word: "1")
say(something: "1")

Input 과 Output 이 모두 있는 것

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
func greet(person: String) -> String {
let greeting = "Hello, " + person + "!" // greet함수 내에서만 사용되는 상수(greeting)
return greeting
}

greet(person: "Anna") // 함수사용

func addNumbers(a: Int, b: Int) -> Int {
return a + b
//한줄만 사용시 return생략 가능 , print를 붙이면 return도 붙여줘야함
}

let x = addNumbers(a: 10, b: 20) // x = 30
let y = addNumbers(a: 3, b: 5) // y = 8
x + y // 38

Input 과 Output 이 모두 없는 것

1
2
3
4
5
6
7
8
let outside = "outside"
func scope() { // 반환값이 없으므로 return 사용 안함
print(outside)
let inside = "inside"
print(inside)
}

scope() // outside; inside;

Argument Label

  • argumentName: 외부에서 호출
  • parameterName: 함수내에서사용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func functionName(argumentName <parameterName>: <Type>) {
}

func someFunction(_ firstParam: Int, secondParam: Int) {
print(firstParam, secondParam)
}

// someFunction(firstParameterName: 1, secondParameterName: 2)
someFunction(1, secondParam: 2)
// _를 넣으면 값만 넣을수있음

func summary(num1 a: Int, num2 b: Int) -> Int {
a + b
}
// 함수 내에서는 a, b로쓰이고 함수 밖에서는 따로 불러서 사용시엔 num1, num2로사용됌

summary(num1: 1, num2: 2)

Variadic Parameters 가변 파라미터

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
func average(_ numbers: Double...) -> Double {
var total = 0.0
for a in numbers {
total += a
}
return total / Double(numbers.count)
}

average(1, 2, 3, 4, 5) // 3
average(3, 8.25, 18.75) // 10

func average1(_ numbers: Double..., and last: Double) {
//네임의 끝을 지정해주거나 첫번째를 지정해줘야함
print(numbers)
print(last)
}

average1(1, 2, 3, and: 5) // [1.0, 2.0, 3.0]; 5.0;
average1(1,2,3,4,5,6, and: 8873646) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]; 8873646.0;

Nested Functions 중첩함수

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/* 
함수 function1을 만들고, 그안에 또다른 함수를 중첩 해넣는다.
if 문을 사용하여 function1의 함수의 파라미터 네임을 사용해 만들어서 true, false일때
다른값이 나오도록 한다.
*/
func function1(backward: Bool, value: Int) -> Int {
func stepForward(input: Int) -> Int {
return input + 1
}
func stepBackward(input: Int) -> Int {
return input - 1
}

if backward {
return stepBackward(input: value)
} else {
return stepForward(input: value)
}
}

var value = 4
chooseStepFunction(backward: true, value: value) // 3
chooseStepFunction(backward: false, value: value) // 5

chooseStepFunction(backward: true, value: 3) // 2
chooseStepFunction(backward: false, value: 3) // 4