Swift와 Objective-C 연결
자동 생성된 Objective-C 생성 헤더를 통해 Swift 코드를 Objective-C에서 사용할 수 있도록 만드는 방법을 학습합니다.
Swift와 Objective-C 연결은(는) CoddyKit의 무료 Objective-C iOS Development for Legacy & Enterprise Apps 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Objective-C iOS Development for Legacy & Enterprise Apps 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Swift to Obj-C: The Bridge
Welcome! In mixed-language projects, you often need Swift code to talk to Objective-C code. This lesson focuses on making your modern Swift classes and methods accessible to older Objective-C files.
This "bridging" allows you to gradually introduce Swift into an existing Objective-C codebase or have parts of your app written in different languages.
The Auto-Generated Header
When you add Swift files to an Objective-C project, Xcode automatically generates a special header file for you. It's named ProductModuleName-Swift.h.
This header acts as a translator, exposing your Swift code to the Objective-C world. You don't create it; Xcode does all the work! You just need to import it.
Exposing Swift Classes
For an Objective-C file to "see" a Swift class, that Swift class must inherit from NSObject. This is a fundamental requirement for Objective-C compatibility.
Without inheriting from NSObject, your Swift class won't appear in the auto-generated bridging header.
Using @objc for Visibility
The @objc attribute explicitly marks a Swift declaration (class, method, property, initializer) as available to Objective-C.
- Classes that inherit from
NSObjectand are notfinalautomatically expose their members. - You might need
@objcfor specific members if your class doesn't inherit fromNSObject(e.g., via a protocol) or for properties/methods that require KVC/KVO compatibility.
A Simple Swift Class
Here's a Swift class, MySwiftGreeter, that inherits from NSObject. Its name property and greet() method will be automatically exposed to Objective-C.
We can optionally use @objc(MySwiftGreeter) to specify the Objective-C name, though it's often inferred.
import Foundation
class MySwiftGreeter: NSObject {
@objc var name: String
@objc init(name: String) {
self.name = name
super.init()
}
@objc func greet() -> String {
return "Hello from Swift, \(name)!"
}
}Importing the Swift Header
To use your Swift classes in an Objective-C file, you simply need to import the auto-generated bridging header. Replace ProductModuleName with your project's actual module name.
This import should be in your Objective-C .m implementation file, not in a .h header file, to avoid circular dependencies and unnecessary exposure.
// In MyObjectiveCFile.m
#import "YourProjectName-Swift.h"
// Now you can use MySwiftGreeter
// ...Using Swift in Obj-C
Once the bridging header is imported, your Objective-C code can create instances of Swift classes and interact with their exposed properties and methods, just like any other Objective-C object.
Note: This code snippet shows how it would look in a project. Running it directly requires a full Xcode project setup with both Swift and Objective-C files.
#import <Foundation/Foundation.h>
#import "MyProjectName-Swift.h" // Your project's auto-generated header
int main(int argc, const char * argv[]) {
@autoreleasepool {
// Create an instance of the Swift class
MySwiftGreeter *greeter = [[MySwiftGreeter alloc] initWithName:@"Coddy"];
// Call a method on the Swift object
NSString *greeting = [greeter greet];
NSLog(@"%@", greeting);
// Access a property
NSLog(@"Greeter's name: %@", greeter.name);
}
return 0;
}Swift & Obj-C Type Map
When bridging, Swift types are automatically mapped to their closest Objective-C equivalents:
- Swift
Stringmaps toNSString* - Swift
Int,Double,Boolmap toNSNumber* - Swift
Arraymaps toNSArray* - Swift
Dictionarymaps toNSDictionary*
This allows seamless data exchange between the two languages.
Customizing Obj-C Names
Sometimes, Swift's inferred Objective-C name for a class or method might not be ideal, or it might conflict. You can provide a custom Objective-C name using @objc(NewName).
This is especially useful if you need to match existing Objective-C naming conventions or avoid clashes with existing Objective-C symbols.
import Foundation
@objc(LegacyGreeter) // Renames MySwiftGreeter to LegacyGreeter for Obj-C
class MySwiftGreeter: NSObject {
@objc var name: String
@objc(initWithPersonName:) // Custom name for initializer
init(name: String) {
self.name = name
super.init()
}
@objc(sayHello) // Custom name for method
func greet() -> String {
return "Hello from Swift, \(name)!"
}
}Bridging Limitations
Not all Swift features can be directly exposed to Objective-C. Keep these limitations in mind:
- Swift Structs & Enums: Unless they have raw values and conform to
@objc, they aren't directly visible. - Generics: Swift generics are not exposed.
- Global Functions: Only methods within
NSObject-derived classes are bridged. - Tuples: Swift tuples have no Objective-C equivalent.
Focus on classes, methods, and properties that mirror Objective-C's object model.
Bridging Knowledge Check
Which of the following is REQUIRED for a Swift class to be accessible from Objective-C code via the auto-generated bridging header?
Bridging Swift to Obj-C
You've learned how to make your Swift code available to Objective-C! Key takeaways:
- Xcode generates a
ProductModuleName-Swift.hheader. - Swift classes must inherit from
NSObjectto be seen by Objective-C. - The
@objcattribute explicitly exposes members or renames them. - Swift types like
String,Array, andDictionaryare automatically mapped to theirNScounterparts.
This bridging is crucial for maintaining and evolving mixed-language iOS projects!
자주 묻는 질문
“Swift와 Objective-C 연결” 강의는 무료인가요?
네 — “Swift와 Objective-C 연결” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Objective-C iOS Development for Legacy & Enterprise Apps 강의 전체를 잠금 해제할 수 있습니다. Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 총 4개의 강의가 포함되어 있습니다.
“Swift와 Objective-C 연결”에서 뭘 배우나요?
자동 생성된 Objective-C 생성 헤더를 통해 Swift 코드를 Objective-C에서 사용할 수 있도록 만드는 방법을 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 Objective-C iOS Development for Legacy & Enterprise Apps을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Objective-C iOS Development for Legacy & Enterprise Apps을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Objective-C iOS Development for Legacy & Enterprise Apps은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.
“Swift와 Objective-C 연결” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Objective-C iOS Development for Legacy & Enterprise Apps 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Objective-C iOS Development for Legacy & Enterprise Apps 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- Objective-C와 Swift 연결
- Swift와 Objective-C 연결
- Objective-C 프레임워크 만들기
- 브리지 간 널 허용 여부와 타입 매핑 처리