#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) } }原文链接:https://www.f2er.com/swift/326688.html