OC調用Swift

來源:互聯網
上載者:User

標籤: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的類來調用,一定要繼承自NSObjectclass 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

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.