C++ · Swift 코드 비교
이 코스 레슨에 나오는 같은 프로그램을 두 언어로 나란히 보여 줍니다: C++, Swift.
바인딩과 가변성
C++의 auto는 타입 추론을 요청하며, 그 자체로 지역 변수를 불변으로 만들지는 않습니다. const는 별도의 제한을 추가합니다. Swift도 마찬가지로 고정된 타입을 추론하지만, let과 var를 명시적으로 구분합니다. C++의 const 객체는 런타임에 초기화할 수 있지만, constexpr는 추가적인 상수 표현식 규칙을 적용합니다. Swift의 let도 런타임 초기화를 허용합니다. 예제에서는 문자열을 다시 할당한 다음 레이블을 보존합니다. C++에서…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14auto mode = std::string("draft");15 mode = "ready";16 const auto label = mode;17 std::cout << label << '\n';18}Swift1var mode = "draft"2mode = "ready"3let label = mode4print(label)문자열과 보간법
C++은 스트림, 문자열 연결 또는 포맷팅 라이브러리를 사용해 서식 지정된 텍스트를 만들 수 있는 반면, Swift는 백슬래시와 괄호를 사용하여 String 내에서 표현식을 직접 보간합니다. std::string은 값 의미론과 변경 가능한 문자 저장소를 가지며, 이를 복사하더라도 일반적으로 동일한 가변 문자열 객체에 대한 두 번째 참조가 생성되지 않습니다. Swift String 또한 값 의미론을 가지지만, 정수로 바이트를 인덱싱하는 대신 Character…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14int side = 4;15 std::cout << side << " squared = " << side * side << '\n';16}Swift1let side = 42print("\(side) squared = \(side * side)")Switch문과 패턴
C++ switch는 정수 또는 열거형 조건을 허용하며 제어가 빠져나가지 않는 한 case 본문 간의 fallthrough를 허용합니다. Swift switch는 문자열과 더 풍부한 패턴을 지원하며 case를 자동으로 종료합니다. 그 커버리지는 가능한 모든 입력 또는 default를 포함해야 합니다. 소스는 1바이트 명령 문자를 비교하고, 타겟은 전체 문자열 명령을 받습니다. 인접한 C++ case 레이블은 본문을 공유할 수 있는 반면, Swift는 하나의…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14char command = 'w';15 switch (command) {16 case 'w': case 's': std::cout << "write\n"; break;17 default: std::cout << "ignore\n"; break;18 }19}Swift1let command = "w"2switch command {3case "w", "save": print("write")4default: print("ignore")5}함수와 레이블
C++와 Swift는 모두 자유 함수와 기본 인자를 지원하지만, 일반적인 C++ 호출은 Swift의 외부 인자 레이블을 사용하지 않습니다. Swift는 호출 지점에서의 레이블과 함수 내부의 매개변수 이름을 구분하며, 밑줄은 해당 외부 레이블을 생략합니다. 명시적인 로컬 복사본이나 inout 계약이 설계를 변경하지 않는 한, Swift 함수에서 매개변수는 상수 바인딩입니다. 예제는 구분자로 연결된 텍스트를 반환하며, 출력 작업은 호출자의 책임입니다. times와…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12std::string repeat_text(const std::string &text, int times) {13 std::string result;14 for (int i = 0; i < times; ++i) { if (i) result += "/"; result += text; }15 return result;16}17 18int main() {19std::cout << repeat_text("ha", 3) << '\n';20}Swift1func repeatText(_ text: String, times: Int) -> String {2 return Array(repeating: text, count: times).joined(separator: "/")3}딕셔너리와 누락된 키
C++ std::map::operator[]는 존재하지 않는 키에 대해 기본값을 삽입하는 반면, find는 삽입 없이 부재 상태를 확인하고 at은 존재하지 않는 항목에 대해 예외를 발생시킵니다. Swift Dictionary의 일반 조회는 Optional을 반환하며, 서브스크립트를 통해 nil을 할당하면 매핑이 제거됩니다. 읽기 동작이 상태를 변경할 수 있는지 여부에 맞춰 적절한 조회 API를 선택하세요. 예제에서는 zoom을 제거하고 기본 대체값으로 100을…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12 13int main() {14std::map<std::string, int> settings{{"zoom", 125}};15 settings.erase("zoom");16 auto found = settings.find("zoom");17 std::cout << (found == settings.end() ? 100 : found->second) << '\n';18}Swift1var settings = ["zoom": 125]2settings["zoom"] = nil3print(settings["zoom"] ?? 100)구조체와 독립적인 복사본
C++의 기본 멤버별 복사와 Swift의 구조체 대입은 각 필드의 의미를 보존합니다. std::string 멤버는 값을 복사하는 반면, shared_ptr 멤버는 동일한 피지시 대상에 대한 공유 소유권을 유지합니다. 이 예시에서 Swift의 String 값과 클래스 참조 필드도 이와 비슷한 차이가 있습니다. 복사본의 레이블을 변경해도 원래 레이블은 그대로지만, 공유 셀을 변경하면 두 복사본 모두에서 변경 사항이 보입니다. C++는 사용자 지정 복사 연산을…
C++1#include <iostream>2#include <string>3#include <vector>4#include <map>5#include <set>6#include <optional>7#include <memory>8#include <tuple>9#include <variant>10#include <stdexcept>11#include <algorithm>12struct Cell { std::string text; };13struct LabelledBox { std::string label; std::shared_ptr<Cell> shared; };14 15int main() {16LabelledBox original{"old", std::make_shared<Cell>(Cell{"one"})};17 auto copy = original;18 copy.label = "new";19 copy.shared->text = "two";20 std::cout << original.label << ' ' << original.shared->text << '\n';21}Swift1final class Cell { var text: String; init(text: String) { self.text = text } }
강의계획서
10 챕터48 강의1 프로젝트48 도전과제99 퀴즈 문항텍스트와 조건 판단
5 강의제어 흐름
5 강의함수와 배열
5 강의컬렉션 도구
5 강의값과 참조
5 강의실패와 추상화
6 강의타입 설계
6 강의C++ 포팅
2 강의자주 묻는 질문
C++ 개발자를 위한 Swift은(는) 누구를 위한 코스인가요?
이미 C++ 코드를 쓸 줄 알고 Swift 언어를 배우려는 분을 위한 코스입니다. 각 레슨은 익숙한 C++ 코드에서 시작해 Swift 언어에서는 같은 일을 어떻게 하는지 보여 주므로, 초보자용 기초는 건너뛸 수 있습니다.
Swift 언어를 미리 알아야 하나요?
아니요. 코스는 첫 Swift 프로그램부터 시작합니다. 필요한 것은 C++ 기초입니다: 변수, 조건문, 반복문, 함수, 컬렉션.
C++ 개발자를 위한 Swift에는 강의가 몇 개 있나요?
C++ 개발자를 위한 Swift에는 자기 페이스에 맞게 진행할 수 있는 48개의 인터랙티브 강의가 포함되어 있습니다.
C++ 개발자를 위한 Swift은(는) 무엇을 다루나요?
코스는 다음 챕터로 구성됩니다: Swift 시작하기, 텍스트와 조건 판단, 제어 흐름, 함수와 배열, and more.
C++ 개발자를 위한 Swift은(는) 무료인가요?
네. Coddy의 모든 코스는 무료로 시작할 수 있습니다. 다운로드나 가입 없이 브라우저에서 강의를 진행할 수 있습니다.