gpt4 book ai didi

swift - 将 Obj-C 通过引用转换为 Swift

转载 作者:可可西里 更新时间:2023-11-01 01:06:53 24 4
gpt4 key购买 nike

我正在尝试将一个简单的方法从 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 调用方法/函数:

unichar c;
[myObject getChar:&c];

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

最佳答案

编辑:我看到您正在尝试使用 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在单独的闭包中以不安全的方式访问值。这可能是为了避免程序员因指针错误而出错。

关于swift - 将 Obj-C 通过引用转换为 Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com