OC調用Swift
阿新 • • 發佈:2017-06-17
nslog ring desc urn with 主動 轉換 oot override
OC文件:Root.h
Root.m
Swift文件:Person.swift
改動main.m文件
#import <Foundation/Foundation.h> #import "Root.h" int main(int argc, const char * argv[]) { @autoreleasepool { Root *rt = [[Root alloc] init]; [rt desc]; } return 0; }
OC文件:Root.h
#import <Foundation/Foundation.h> //Objective-c 的頭文件假設須要引用Swift的類。則能夠使用以下這樣的方式 @class Person; @interface Root : NSObject -(Person *)returnPerson; -(void)desc; @end
Root.m
#import "Root.h" //Objective-c調用Swift //須要導入固定的頭文件。此頭文件項目裏面找不到,但卻是存在。而且會自己主動把Swift類轉換成OC的類,在裏面能找到 //格式為 #ProductName#-Swift.h #import <OC_Swift-Swift.h> @implementation Root -(void)desc { Person *ps = [[Person alloc] initWithName:@"Rose"]; ps.name = @"Jack"; [ps desc]; } -(Person *)returnPerson { Person *ps = [[Person alloc] initWithName:@"Tom"]; return ps; } @end
Swift文件:Person.swift
import Foundation //假設此類須要被OC的類來調用。一定要繼承自NSObject class Person : NSObject { var name: String { willSet { NSLog("將要把名字設置為:" + name) } } override init() { self.name = "" } init(name: String) { self.name = name } func desc() { print("這是一個Swift的類,name: " + self.name) } }
OC調用Swift