Code with Objective C & Swift

最近一時手癢,想說 Swift 可以與 Objective-C 混合使用,立馬參照官方作法Swift and Objective-C in the Same Project以及Swift Type Compatibility

當我使用純Swift物件時,執行狀況並不如預期順利,在 Stack Overflow 的這篇提供了相當不錯的解法

How to call Objective C code from Swift

Using PURE Swift Classes in Objective-C

Step 1 Create New Swift Class

PureSwiftObject.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Foundation

// Note '@objc' prefix
@objc class PureSwiftObject {

var name: String
init(name: String) {
self.name = name
}

// Needed to add a class level initializer
class func newInstanceNamed(name: String) -> PureSwiftObject {
return PureSwiftObject(name: name)
}

// Just a method for demonstration
func someMethod() {
println("Some method ran in pure swift object")
}
}

Step 2 Import Swift Files to ObjC Class

In SomeRandomClass.m:

#import "<#YourProjectName#>-Swift.h"

Step 3 Use your pure swift class

PureSwiftObject.swift
1
2
3
PureSwiftObject * pureSwiftObject = [PureSwiftObject newInstanceNamed:@"Janet"];
NSLog(@"PureSwiftNamed: %@", pureSwiftObject.name);
[pureSwiftObject someMethod];