_ArrayType或_ArrayProtocol在Swift 3.1中不可用吗? [英] Does _ArrayType or _ArrayProtocol not available in Swift 3.1?

查看:105
本文介绍了_ArrayType或_ArrayProtocol在Swift 3.1中不可用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在swift 2.1上运行时,我在项目中使用了_ArrayType.我上周升级到Swift 3.0.2(Xcode 8.2.1),发现在这里_ArrayType更改为_ArrayProtocol并且运行良好.

I was using _ArrayType in my project when I was running on swift 2.1. I upgraded to swift 3.0.2 (Xcode 8.2.1) last week and I found here that _ArrayType is changed to _ArrayProtocol and it was working well.

今天,我将Xcode升级到8.3.1,这给了我错误: Use of undeclared type '_ArrayProtocol'.这是我的代码:

Today I upgraded my Xcode to 8.3.1, and it gives me error: Use of undeclared type '_ArrayProtocol'. Here is my code:

extension _ArrayProtocol where Iterator.Element == UInt8 {
    static func stringValue(_ array: [UInt8]) -> String {
        return String(cString: array)
    }
}

现在怎么了?为什么_ArrayProtocol在swift 3.0.2.中工作时未在swift 3.1中声明.

What's wrong now? Why _ArrayProtocol is undeclared in swift 3.1 while it was working in swift 3.0.2.

另外,当我在这里查看在git中我看到_ArrayProtocol可用. 比起我 Swift 2.1文档,我能够在协议列表中看到"_ArrayType",但是在Swift中 3.0 / 3.1 文档我看不到_ArrayProtocol.

Also when I look here in git I see _ArrayProtocol available. Than I looked into Swift 2.1 docs I am able to see '_ArrayType' in protocol listing but in Swift 3.0/3.1 docs I am not able to see _ArrayProtocol.

推荐答案

以下划线开头的类型名称应始终视为内部名称. 在Swift 3.1中,它在源代码中被标记为internal,因此 不公开显示.

Type names starting with an underscore should always treated as internal. In Swift 3.1, it is marked as internal in the source code and therefore not publicly visible.

在早期的Swift版本中,使用_ArrayProtocol是一种解决方法 您无法定义具有相同类型"要求的Array扩展名. 从Swift 3.1开始,这已经成为可能,如

Using _ArrayProtocol was a workaround in earlier Swift versions where you could not define an Array extension with a "same type" requirement. This is now possible as of Swift 3.1, as described in the Xcode 8.3 release notes:

受约束的扩展允许在通用参数和具体类型之间使用相同类型的约束. (SR-1009)

因此不再需要使用内部协议, 您只需定义

Using the internal protocol is therefore not necessary anymore, and you can simply define

extension Array where Element == UInt8 {

}

但是请注意,您的static func stringValue()不需要任何 元素类型的限制.您可能想要的是 像这样定义 instance方法:

But note that your static func stringValue() does not need any restriction of the element type. What you perhaps intended is to define an instance method like this:

extension Array where Element == UInt8 {

    func stringValue() -> String {
        return String(cString: self)
    }

}

print([65, 66, 67, 0].stringValue()) // ABC

还请注意,String(cString:)期望以 null终止的序列 的UTF-8字节.

Also note that String(cString:) expects a null-terminated sequence of UTF-8 bytes.

这篇关于_ArrayType或_ArrayProtocol在Swift 3.1中不可用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆