【问题标题】:Issue with converting NSString * to String and passing Character as parameter in Swift iOS在 Swift iOS 中将 NSString * 转换为 String 并将 Character 作为参数传递的问题
【发布时间】:2015-04-08 08:15:30
【问题描述】:

我使用 Bridging 标头从 Swift 调用 Objective 方法。

-(NSString *) PatternSetCreator: (char)Signature detection_time_in_sec:(int)detection_time_in_sec patternLength:(int)patternLength maxPatternSetSize:(int)maxPatternSetSize

有两个问题:

a) 从 Swift 调用此方法时,我无法将单个字符作为参数传递

b) 我不确定如何获取返回类型 NSString 并将其分配给 String 变量

【问题讨论】:

  • 虽然我是 Objective C 和 Swift 的新手,但我认为这将是在 Objective C 中编写 C 风格的代码。希望有一种方法可以直接调用它。

标签: ios objective-c swift nsstring


【解决方案1】:

Swift 中的单个 C char 表示为 CCharInt8 的类型别名。

(类似地,Swift 中的 C intCIntInt32 的类型别名)

如果你想要一个特定的字符并使用 Swift 1.2,有一个 UInt8 的初始化器,它接受 UnicodeScalar。但是,令人讨厌的是,您必须将其转换为 Int8 以使其与 C 方法兼容:

    let ch = CChar(UInt8(ascii: "x"))
    let i = CInt(100)
    let s = obj.PatternSetCreator(ch, 
                   detection_time_in_sec: i, 
                   patternLength: i, 
                   maxPatternSetSize: i)

您无需执行任何特殊操作即可将返回的NSString 转换为String。桥接会自动完成。

(或者更确切地说,它会返回一个String!——但是如果保证目标c代码每次都返回一个有效的字符串而不是空指针,那么定义可以更改为-(nonnull NSString *) PatternSetCreator: etc…,这意味着它将而是返回String

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多