Swift 공부/정리

DH Song·2025년 2월 4일
0

개요


Fast, Safe, Expressive 목적으로 개발중인 언어

Syntax


  • 세미콜론(;) 생략 가능

  • 변수출력

print(“변수 출력 \(변수명))
  • 자료형 (기본) : Int, Uint, Float, Double, Character, String, Bool, Any, Never
// 변수 선언 예시
var aaa:Int = 10
const ABC:String =Constant
  • nil : 할당되지 않은 경우의 값

Alias (별칭) 지정

typealias MyInt = Int
typealias MyDouble = Double

Tuple

var myTuple: (String, Int, Double) = ("a", 1, 1.0)		// 선언
print("\(myTuple.0), \(myTuple.1), \(myTuple.2)")	// 출력

Collection


Array

var fruitList:Array<String> = ["apple", "banana", "coconut"]
var fruits:[String] = ["apple", "banana", "coconut"]

// method
.first
.last
.append(value)
.append(contentsOf: [value1, value2])	// Array 삽입
.index(of: value)

Set

var animals:Set<String> = Set<String>()		// init.
var animals:Set<String> = ["elephant", "monkey"]	// init. with val.

// method
.remove(value)
.union(animals)			// 합집합
.subtracting(animals)	// 차집합
.intersection(animals)	// 교집합
.isDisjoint(with: animals)	// 상호 베타적인지
.isSubset(of: animals)		// animals에 포함되는지 (animals의 부분집합인지)
.isSuperset(of: animals)	// animals의 포함하는지 (animals의 전체집합인지)

Dictionary
Key, Value 자료구조

var myDict:Dictionary<String, Int> = Dictionary<String, Int>()	// init.
var myDict:Dictionary<String, Int> = ["a": 1, "b":2]	// init. with val.
print(myDict["a"])

// method
.removeValue(forKey: "key")

Enum


Declare

// 1. 일반 선언
enum Zoo {
	case monkey, elephant, rabbit
}

// 2. Raw Value 선언 (일반 선언과 혼합 가능)
enum Zoo:String {
	case monkey = "원숭이"
    case elephant = "코끼리"
    case rabbit = "토끼"
}

// 호출 시
Zoo.monkey

열거형

enum PastaTaste {case cream, tomato}
enum PizzaDough {case cheeseCrust, thin, original}
enum PizzaTopping {case pepperoni, cheese, bacon}

enum MainDish 1 {
	case pasta (taste: PastaTaste)
	case pizza(dough: PizzaDough, topping: PizzaTopping)
	case chicken(withSauce: Bool)
	case rice
}

모든 case 조회 (allCases)

enum AAA: CaseIterable {...}
let allCases: [AAA] = AAA.allCases
  • Override
enum AAA: String CaseIterable{
	case a = "a"
    ...
    
    static var allCases: [AAA] {
    	let all: [AAA] = [.a, .b, ...]
        
        // implement here
        
        return all
    }
}

Operator (연산자)

Boolean

연산자설명
!AA의 bool값 반대
A && BA와 B의 AND 논리 연산
A || BA와 B의 OR 논리 연산

Bit

연산자설명
~AA의 bit 반전
A & BA와 B의 AND 논리 연산
A | BA와 B의 OR 논리 연산
A^BA와 B의 XOR 논리 연산
A >> BA를 B만큼 우측 이동
A << BA를 B만큰 좌측 이동

전/중/후위 연산자
전위 연산자(prefix), 중위 연산자(infix), 후위 연산자(postfix)를 정의해 사용 가능

Functions


  • dump() : print() 보다 자세한 정보 출력
  • collection method
    - shuffle() : collection 섞기
    • shuffled() : 섞인 collection 반환 (본래 객체는 유지)
    • randomElement() : collection에서 임의의 원소값 하나 반환

흐름 제어


조건문

반복문

Hot-key


Xcode

[option] + click : 퀵헬프, 함수옵션 및 설명

0개의 댓글

관련 채용 정보