오늘에 진행할 목록들
- 저번에 했던 내용 복습
(내용이 많습니다. 스압주의!)
또한 이번주차부터 예시코드도 같이 올라갑니다.
1. 데이터 타입 (자료형)들
https://www.onlinegdb.com/online_swift_compiler
(swift 언어 연습용 홈페이지)
Online Swift Compiler - online editor
OnlineGDB is online IDE with swift compiler. Quick and easy way to run swift scripts online.
www.onlinegdb.com
참고 : 일반적으로는, 초기값을 안줄때만 자료형을 쓰는편
초기값이 있다면 굳이 자료형을 쓸 이유는 없음
1-1. 정수 데이터 타입 : Int
print(Int.min) // 최소값
print(Int.max) // 최대값
// 64비트 기준
min : -9,223,372,036,854,775,808
max : 9,223,372,036,854,775,807
//32비트 기준
min : -2,147,483,648
max : 2,147,483,647
1-2. 부동 소수점 데이터 타입 : Double , Float
1-3. 문자 데이터 타입 : character
1-4. 문자열 데이터 타입 : String
1-5. 특수 문자 / 이스케이프 시퀀스
1-6. 변수 : var
var x = 10
var y = 20
print(x,y)
1-7. 상수 : let
let x = 10
let y = 20
print(x,y)
//y = 30
//error: cannot assign to value: 'y' is a 'let' constant
//change 'let' to 'var' to make it mutable
1-9. 튜플 : Tuple
// 튜플 종합
let myTuple = (10, 12.1, "Hi")
print(type(of: myTuple)) //자료형 알아내기
// 선택 추출후 출력
var (myInt, _, myString) = myTuple //12.1 무시
// 각 값에 이름 할당하기
let myTuple = (count: 10, length: 12.1, message: "Hi")
(count: Int, length: Double, message: String)
// 튜플의 메세지값 호출
print(myTuple.message, myTuple.2)
//Hi Hi
2. 옵셔널 타입 / Nullable type
관련 자료 : https://en.wikipedia.org/wiki/Option_type
Option type - Wikipedia
From Wikipedia, the free encyclopedia Encapsulation of an optional value in programming or type theory For families of option contracts in finance, see Option style. In programming languages (especially functional programming languages) and type theory, an
en.wikipedia.org
2-1. Int , Optional Int
2-2. 옵셔널 타입?
2-3(1). 옵셔널 타입 강제 언래핑
var x : Int?
var y : Int = 0
x = 10 // 주석처리하면? 난리남
print(x) // Optional(10)
print(x!)
print(y)
// x = x + 2 불가능
// y = x 불가능
2-3(2). 강제 언래핑시 주의사항
2-4. 옵셔널 바인딩 (강제 언래핑 2)
2-5. Short form of if-let to the optional binding 예시
//기본 코드
var pet1: String?
var pet2: String?
pet1 = "cat"
pet2 = "dog"
if let firstPet = pet1, let secondPet = pet2
{ print(firstPet, secondPet) }
else { print("nil") }
//short form of if-let to the Optional Binding
var pet1: String?
var pet2: String?
pet1 = "cat"
pet2 = "dog"
if let pet1, let pet2 { print(pet1, pet2) }
else { print("nil") }
2-6. 언래핑하는 여러가지 방법
2-7. 암묵적인 언래핑 옵셔널 ( ? , ! )
2-8. 두가지 옵셔널 비교
let x : Int? = 1
let y : Int = x!
let z = x
print(x,y,z) //Optional(1) 1 Optional(1)
print(type(of:x),type(of:y),type(of:z))
//Optional<Int> Int Optional<Int>
let a : Int! = 1 //Implicitly Unwrapped Optional
let b : Int = a //Optional로 사용되지 않으면 자동으로 언래핑
let c : Int = a!
let d = a //Optional로 사용될 수 있으므로 Optional형임
let e = a + 1
print(a,b,c,d,e) //Optional(1) 1 1 Optional(1) 2
print(type(of:a),type(of:b),type(of:c),type(of:d), type(of:e))
2-9. 옵셔널을 사용하는 이유?
2-10. nil
You set an optional variable to a valueless state by assigning it the special value nil.
당신이 선택한 변수를 값이 없다는것을 할당하려면 nil을 사용하세요.
3. 연산자 관련 문서
https://developer.apple.com/documentation/swift/swift_standard_library/operator_declarations
Operator Declarations | Apple Developer Documentation
Work with prefix, postfix, and infix operators.
developer.apple.com
https://www.programiz.com/swift-programming/operator-precedence-associativity
Swift Operator precedence and associativity (With Examples)
Operator precedence is a set of rules that determines which operator is executed first. Before you learn about operator precedence, make sure to know about Swift operators. Let's take an example, suppose there is more than one operator in an expression. va
www.programiz.com
https://docs.swift.org/swift-book/documentation/the-swift-programming-language/basicoperators/
Documentation
docs.swift.org
3-1. 대입 연산자
3-2. 산술 연산자
3-3. 복합 대입 연산자
3-4. 증감 연산자
3-5. 비교 연산자
3-6. 논리 연산자
3-7. 범위 연산자
//닫힌 범위 연산자
x...y
x에서 시작하여 y로 끝나는 범위에 포함된 숫자
5...8
//5, 6, 7, 8
//반 열린 범위 연산자
x..<y
//x부터 시작하여 y가 포함되지 않는 모든 숫자
5..<8
//5, 6, 7
//One-Sided Ranges
let names = ["A", "B", "C", "D"]
for name in names[2...] { //[...2], [..<2] print(name) }
//[...2] = A B C
//[..<2] = A B
3-8. 삼항 연산자
3-9. nil 병합 연산자
let defaultColor = "black"
var userDefinedColor: String? // defaults to nil
var myColor = userDefinedColor ?? defaultColor
//nil이므로 defaultColor인 black으로 할당됨
//쉽게 말해 nil이면 으론쪽에 있는 defaultcolor의 값을 넣고, 아니면 무시
print(myColor) //black
userDefinedColor = "red"
myColor = userDefinedColor ?? defaultColor
//nil이 아니므로 원래 값인 red가 할당됨
print(myColor) //red, 주의 optional(red)가 아님
let defaultAge = 1
var age : Int?
age = 20
print(age) //optional (20)
//age가 nil이 아니므로 언래핑된 값이 나옴
var myAge = age ?? defaultAge
print(myAge) //20
//요것도 nil이 아니라서 강제로 언래핑됨
var x : Int? = 1
var y = x ?? 0
print(y) //1
4. 클래스 , 객체 , 인스턴스
4-1. 형 변환
5. 제어문 (for in , if ~ else , while , repeat ~ while , switch ~ case....)
5-1. for - in 반복문
for i in 1...5 {
print("\(i) Hello")
}
5-2. while 반복문
var myCount = 0
while myCount < 1000
{ myCount+=1 }
print(myCount)
//1000
//myCount가 0부터 시작하여 1000보다 작다면 계속 1씩 증가시킴
5-3. repeat ~ while 반복문
var i = 10
repeat { i=i-1
print(i) }
while (i > 0)
//7 6 5 4 ... 0
//i가 0보다 크다면 1씩 계속 감소시킴
5-4. break
for i in 1..<10 {
if i > 5 break //<<이렇게 쓰면 에러
print(i)
}
for i in 1..<10 {
if i > 5 { break } //<<이렇게 써야 에러 방지 가능
print(i)
}
5-5. continue
for i in 1...10 {
if i % 2 == 0 { continue }
//2로 나누어 떨어지는수를 출력하고, 반복문을 끝낼때까지 다시 돌아감
print(i)
}
5-6. if문
//첫번째
var x = 10
if x > 5 { print("5보다 큽니다") }
//두번째
var x = 1
var y = 2
if x == 1 && y==2 { //논리식이 둘 다 참일 때
print(x,y)
}
if x == 1, y==2 { //조건이 둘 다 참일 때, 두 조건을 콤마로 연결한 condition-list
print(x,y)
}
var a : Int? = 1
var b : Int? = 2
print(a,b)
if let a1=a, let b1=b { //a와 b가 nil이 아니면, 언래핑하여 a1과 b1에 대입
print(a1,b1)
}
// if let a1=a && let b1=b { //error: expected ',' joining parts of a multi-clause condition
// print(a1,b1)
// }
5-7. 단일 or 다중 if ~ else 문
5-8. 다중 if ~ else 문으로 BMI 계산기 만들기
let weight = 60.0
let height = 170.0
let bmi = weight / (height * height * 0.0001) // kg/m*m
var body = ""
if bmi >= 40 {
body = "3단계 비만"
} else if bmi >= 30 && bmi < 40 {
body = "2단계 비만"
} else if bmi >= 25 && bmi < 30 {
body = "1단계 비만"
} else if bmi >= 18.5 && bmi < 25 {
body = "정상"
} else {
body = "저체중"
}
print("BMI:\(bmi), 판정:\(body)")
//switch case인 경우
let weight = 60.0
let height = 170.0
let bmi = weight / (height * height * 0.0001) // kg/m*m
var body = ""
switch bmi {
case 40...:
body = "3단계 비만"
case 30..<40:
body = "2단계 비만"
case 25..<30:
body = "1단계 비만"
case 18.5..<25:
body = "정상"
default:
body = "저체중"
}
print(body)
5-9(1). guard문
5-9(2). if ~ let , guard ~ let
func printName(firstName:String, lastName:String?) {
// if let
if let lName= lastName
{ print(lName,firstName) }
else{ print("성이 없네요!") }
// guard let
guard let lName= lastName else
{ print("성이 없네요!") return }
print(lName,firstName) }
printName(firstName:"길동", lastName:"홍")
printName(firstName:"길동", lastName:nil)
5-9(3). guard let ~ else로 옵셔널 바인딩
5-10. switch ~ case문
5-10(2). switch ~ case문 주의사항
error: 'case' label in a 'switch' should have at least one executable statement.
오류: 'switch'의 'case' 문에는 최소한 실행 가능한 코드가 하나 이상 있어야 합니다.
5-11. switch ~ case문 결합하기
5-11. switch ~ case문 범위 지정
5-12. switch ~ case문 + where절
//성적 기반 코드 (iOS프로그래밍 2주차 참고)
let score = 91
switch score {
case 90...100 where score >= 95:
print("A+")
case 90...100:
print("A")
case 80..<90 where score >= 85:
print("B+")
case 80..<90:
print("B")
.....
//거리 코드 (기본단위는 m)
var range = 750
switch (temperature)
{
case 0...1000 where range >= 500:
print("500m 이하")
case 0...1000 where range =< 500:
print("500 이상")
.....
5-13. where : 조건 추가
5-13. fallthrough
6. 함수
6-1. 메서드
6-2. 함수를 선언하는 방법
6-3. 기초적인 함수정의 , 호출
'실무 (iOS)' 카테고리의 다른 글
iOS프로그래밍 실무 (6주차) [옵셔널 체이닝 , Error handling , generic , array] (0) | 2025.04.10 |
---|---|
iOS 프로그래밍실무 (5주차) [프로토콜,Xcode 앱만들기] (0) | 2025.04.06 |
iOS프로그래밍 실무 (4주차) [함수,클래스,프로토콜] (0) | 2025.03.27 |
iOS프로그래밍 실무[3주차] 앱 만들기 복습 (0) | 2025.03.25 |
iOS 프로그래밍 실무 [1주차] (0) | 2025.03.09 |
댓글