翻译Obj-C通过引用传递给Swift

时间:2014-06-06 21:29:17

标签: swift

我正在尝试将一个简单的方法从Obj-C转换为Swift,我无法从文档中找到解决方法。

我已经将方法简化为一个简单的例子,说明了我不理解的内容:

- (void)getChar:(unichar *) outChar
{
    *outChar = 'a';
}

到目前为止,我在Swift中最接近这个是:

func getChar(inout outChar:CMutablePointer<unichar>) -> () 
{
    outChar = ("a" as NSString).characterAtIndex(0)
}

但我当然得到了第3行的错误:Unichar无法转换为CMutablePointer。

BuildingCocoaApps pdf有关于使用Obj-C指针的简短部分,但我无法弄清楚它与它的关系。

有人可以解释一下如何做到这一点吗?

编辑: 我正在调用Obj-C中的方法/ func,如下所示:

unichar c;
[myObject getChar:&c];

我意识到我需要在func之前添加@objc,因为我是从Obj-C调用的。而这现在给了我更多的错误。

1 个答案:

答案 0 :(得分:3)

编辑:我看到你正在尝试使用Obj-C中的Swift类方法。

确保您的Obj-C实施文件(.m)具有Swift导入
#import <##Your-Project-Name##>-Swift.h
此文件在您的项目中不可见,但需要导入才能在Obj-C中使用Swift类(请参阅Apple documentation)。

我在main.m

中创建了一个Obj-C命令行程序
#import <Foundation/Foundation.h>
#import "ObjCTest-Swift.h"  // <- VERY IMPORTANT!

int main(int argc, const char * argv[])
{
    @autoreleasepool
    {
        unichar someChar = '\0';

        // This is my Swift class
        TextGenerator *textGenerator = [[TextGenerator alloc] init];
        [textGenerator generateChar:&someChar];

        NSLog(@"Character vaue is now %d", someChar);
    }

    return 0;
}

随附的TextGenerator.swift文件:

import Foundation

@objc class TextGenerator : NSObject
{
    @objc func generateChar(outChar:CMutablePointer<unichar>)
    {
        let testString : NSString = "The quick brown fox jumps over the lazy dog."
        let firstChar = testString.characterAtIndex(0)

        // Access the unichar * in an unsafe context to set the value directly
        outChar.withUnsafePointer{ charPtr in charPtr.memory = firstChar }

        // Alternatively, this is the shorthand form ($0 is the first arg)
        outChar.withUnsafePointer{ $0.memory = firstChar }
    }
}

真正的好处是你不能直接改变CMutablePointer<Type>存储的值。您必须使用withUnsafePointer以不安全的方式在单独的闭包中访问该值。这可能是为了避免程序员错误导致指针失误。