相关疑难解决方法(0)

如何在Swift中将UInt8字节数组转换为字符串

UInt8在使用swift 将Byte数组转换为字符串时遇到问题.我搜索并找到一个简单的解决方案

String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)

但它显示错误String.type没有成员stringWithBytes.谁能建议我一个解决方案?

这是我的代码,我得到一个NSData并转换为字节数组,然后我必须将该字节数组转换为字符串.

let count = data.length / sizeof(UInt8)
var array = [UInt8](count: count, repeatedValue: 0)
data.getBytes(&array, length:count * sizeof(UInt8))
String.stringWithBytes(buff, encoding: NSUTF8StringEncoding)
Run Code Online (Sandbox Code Playgroud)

arrays swift

43
推荐指数
7
解决办法
6万
查看次数

使用Swift的C API

我正在尝试跟踪网络状态.我查看了FXReachability的代码.具体如下方法.

- (void)setHost:(NSString *)host
{
    if (host != _host)
    {
        if (_reachability)
        {
            SCNetworkReachabilityUnscheduleFromRunLoop(_reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
            CFRelease(_reachability);
        }
        _host = [host copy];
        _status = FXReachabilityStatusUnknown;
        _reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [_host UTF8String]);
        SCNetworkReachabilityContext context = { 0, ( __bridge void *)self, NULL, NULL, NULL };
        SCNetworkReachabilitySetCallback(_reachability, ONEReachabilityCallback, &context);
        SCNetworkReachabilityScheduleWithRunLoop(_reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes);
    }
}
Run Code Online (Sandbox Code Playgroud)

它的作用是不断检查与指定主机的连接.我正在尝试将此方法转换为Swift,我遇到了一些问题.

1.将主机字符串转换为UTF8.

我必须将主机字符串转换为UTF8并将其传递给SCNetworkReachabilityCreateWithName方法.我无法UTF8String在Objective-C中找到Swift的确切属性.但是,有一个叫做属性utf8String类型.根据文件,

您可以通过迭代其utf8属性来访问String的UTF-8表示.此属性的类型为String.UTF8View,它是无符号8位(UInt8)值的集合,一个用于字符串的UTF-8表示形式中的每个字节:

如何获得字符串的完整UTF8表示而不是无符号8位(UInt8)值的集合?


2. SCNetworkReachabilitySetCallback的回调函数.

此函数的第二个参数需要某种类型SCNetworkReachabilityCallBack.我潜入了源文件,发现它实际上是一个typealias.

typealias SCNetworkReachabilityCallBack = CFunctionPointer<((SCNetworkReachability!, …
Run Code Online (Sandbox Code Playgroud)

c callback utf-8 ios swift

4
推荐指数
1
解决办法
3810
查看次数

将 Swift 字符串传递给 C

我对 Swift 还是很陌生,而且我对 C 的接触不多。

我正在尝试用 C 编写一个函数,该函数将获得一个 Swift 字符串,然后我可以用它做一些事情。问题是我不能 100% 确定 Swift 中的类型应该是什么才能使 C 看起来像它所看到的那样。

到目前为止,我在 Stack 上找到了几个看起来不错的例子,但对于当前版本的 Swift 来说,有些例子似乎已经过时了。

我首先使用这个例子让 C 和 Swift 相互交谈:Swift call C call Swift? 然后我接受了它并尝试更新 Swift 函数以返回某种字符串。我知道它需要是 UTF-8 返回类型,但我不确定如何正确发送内容。我看过如何将 Swift 字符串传递给 ac 函数?如何将 String 转换为 UnsafePointer<UInt8> 和 length,以及如何在 Swift 中将字符串转换为 unicode(UTF-8) 字符串?,但它们中没有一个真正适用于解决方案。或者我只是输入错误。到目前为止,我最接近返回的东西如下。

在 Swift 中,我ViewController是:

import UIKit

class ViewController: UIViewController {

    @_silgen_name("mySwiftFunc") // give the function a C name
    public func mySwiftFunc(number: Int) -> [CChar] …
Run Code Online (Sandbox Code Playgroud)

c ios swift

2
推荐指数
1
解决办法
511
查看次数

标签 统计

swift ×3

c ×2

ios ×2

arrays ×1

callback ×1

utf-8 ×1