Swift 기본기

지니🧸·2023년 4월 9일
0

Swift

목록 보기
3/4
import Founation

var tmp: Int = 3
let constant: String = ""

변수명 짓기

일반적으로는 Camel case 사용

var thisIsVariable: Int = 3 // Camel case

let THIS_IS_CONSTANT = 5 // let으로 선언하면 값이 변할 수 없음

Swift Type

다른 언어에 비해 강하게 잡음

  • Int: 정수형

  • String: 문자열

  • Double: 32비트 실수

  • Float: 64비트 실수

  • Bool

  • Character: 글자 하나

  • Array

  • Map

타입 만들기:

  • struct
  • class
  • enum

Type 확인해보기

print(type(of: -10...10))
  • ClosedRange<Int> 출력

변수 선언

let constant = "문자열" // 타입 생략 가능

let arr: Array<Int> = [1, 2, 3, 4, 5] // <Int> 생략 가능
let arr1: [int] = arr

Array 메서드

  • map
  • count

Dictionary

let dic: Dictionary<String, Int> = [:]
let dic2: Dictionary<String, Int> = Dictionary<String, Int>();
  • String이 키, Int가 value
  • dictionary에 추가하는 값을 찾으면 Optional로 반환

Optional

var tmp: Int?
print(tmp) // nil

Optional Unwrapping하는 방법

  1. 느낌표
print(tmp!) // 이 경우에는 tmp의 값이 nil이거나 Int 값이 아니면 에러가 뜸
  1. If 문 사용:
  • tmp의 값이 valid하게 존재하면 if 문 내에서 사용 가능
  • 구문 밖에서는 사용 불가
if left tmp = tmp {
	...
} else {
	...
}
  1. guard let
  • guard let 뒤의 boolean이 참일 경우 실행
  • 거짓일 경우 else 구문 실행
    • else 구문에서는 return, break, continue, throw 등의 제어문 전환 명령어 사용해야 함
guard let tmp == tmp else {
	// tmp == nil
    
    return
}
  1. tmp가 nil이면 물음표 오른쪽의 값 출력: 입력값이 nil인 경우를 위해 기본값 설정
print(tmp ?? 4)

함수

Swift에서 함수는 변수로 저장할 수 있고 다른 함수의 파라미터로도 넘길 수 있다

func <함수 이름>(<전달인자 레이블> <매개변수 이름>: <타입>, ...) -> 반환 타입 {}

  • 레이블은 가독성을 위함, 필수적이지는 않아서 _로 대체 가능

함수 이름의 첫단어는 명령어 동사

func printGrade(userName: String, score grade: Int) {
	print("\(userName)'s grade is \(grade).")
}

printGrade("becooq", score: 10)

조건문

if true {

} else if {
	
} else {

}
  • boolean 값에 소괄호 필요 없음

switch 문

let temperature = 10

switch temperature {
	case -20..<-5: // 범위
    	print("a"
    case -6...-1, 10...11:
    	print("doSomething")
    default:
}
  • case 하나가 완성되면 break가 없어도 swift 밖으로 진행됨

Enum

enum School {
	case elementary
    case middle
    case high
}

let school: School = .elementary

switch school {
case .elementary:
case .middle:
case .high:
}

for 문

  • for <순회할 상수> in <순회할 대상> {}
for i in -10...10 {
	print(i)
}
  • -10...10: inclusive 범위
    • -10..<10: exclusive

while 문

var i = 1

while i < 10 {
	i == 7 {
    	break
    }
    print(i)
    i += 1
}

OOP & POP

Protocol-Oriented Programming: OOP를 조금 더 상업적으로 만듬

  • Protocol: 다른 언어의 interface

struct/class명은 camel case를 유지하되 첫글자도 대문자

struct

struct <구조체 이름> {
	property, method
}

예시

struct UserInfo {
	var nickName: String
    let age: Int
	
    func printInfo() {
    	print("nickName: \(nickName), age: \(age)")
    }
}

var userAInfo = UserInfo(nickName: "A", age: 15)
var userA = userAInfo // 포인터가 같은 것을 가르키는게 아닌, 복사본을 받아옴
userA.nickName = "AA"

print(userAInfo) // UserInfo(nickName: "A", age: 15)
print(userA) // UserInfo(nickName: "AA", age: 15)
  • 생성자는 init으로 만들 수도 있지만 기본적으로 제공되는 것을 주로 사용

class

class UserInfo {
	var nickName: String
    let age: Int
    
    init(nickName: String, age: Int) {
    	self.nickname = nickname
        self.age = age
    }
    
    func printInfo() {
    	print("nickName: \(nickName), age: \(age)")
    }
}

let userAInfo = UserInfo(nickname: "a", age: 15)
var userA = userAInfo
userA.nickname = "AA"

dump(userAInfo)
dump(userA)
  • 클래스 변수를 참조하면 주소값을 받기 때문에 userA의 속성을 바꿨을 때 userAInfo의 속성도 바뀜
  • struct와 다르게 생성자가 필수적임

Extension

기존 클래스에 추가적으로 메서드를 늘리는 것

extension <클래스명> {
	func addSubviews(_ views: [UIView]) {
    	views.forEach { self.addSubview($0) }
    }
}

Protocol

인터페이스와 비슷한 개념

Closure

  • Swift의 함수는 함수명이 존재하는 closure이다
  • Closure는 클래스처럼 동작할 수 있다
let hello = { () -> () in
	print("hello")
}

hello()
  • 레이블 인자는 존재하지 않음
func doSomething(closure: (Int, Int, Int) -> Int) {
	closure(1, 2, 3)
}

doSomething(closure: { (a, b, c) in 
	return a + b + c
})

doSomething(closure: {
	print($0 + $1 + $2)
})

ARC에 유의하면서 코딩하자

  • 메모리 누수에 취약하다
func makeIncrementer(forIncrement amount: Int) -> () -> Int {
  var runningTotal = 0
  func incrementer() -> Int {
    runningTotal += amount
    return runningTotal
  }
  return incrementer
}

let plusTen = makeIncrementer(forIncrement: 10)
let plusSeven = makeIncrementer(forIncrement: 7)

print(plusTen()) // 10
print(plusTen()) // 20
profile
우당탕탕

0개의 댓글