码迷,mamicode.com
首页 > 编程语言 > 详细

OC调用Swift

时间:2015-07-09 16:15:42      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:swift   oc   调用   

修改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

标签:swift   oc   调用   

原文地址:http://blog.csdn.net/pengyuan_d/article/details/46816993

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!