gpt4 book ai didi

swift - 隐式公共(public)访问 (Bool) 内部类型 'Builtin.Int1' : runtime exception if appending instances of 'Int1' to an array

转载 作者:搜寻专家 更新时间:2023-10-31 22:32:37 25 4
gpt4 key购买 nike

问题

  • 我知道我可能不应该摆弄内置类型,但我很好奇,Builtin.Int1 类型是否真的可以公开访问,如下所示?如果是这样,为什么将它用作数组元素会导致 Swift 崩溃?

我很好奇,因为我从来没有遇到过我自己无法存储在数组中的自定义类型(但我猜内置类型与我可以使用“构建自己的类型不同”公共(public) swift ”)。

我使用的是 Swift 2.2 和 Xcode 7.3。


详情

查看 swift/stdlib/public/core/Bool.swift 的源代码,我们注意到我们可以隐式访问内部类型 Builtin.Int1(1 位整数),它构成了 Swift 中 Bool 类型的基础。

public struct Bool {
internal var _value: Builtin.Int1

// ...

}

extension Bool : Boolean {
// ...
public func _getBuiltinLogicValue() -> Builtin.Int1 {
return _value
}

// ...
}

因此,使用 _getBuiltinLogicValue(),我们可以构造一个 Builtin.Int1 类型的值,并使用它声明一个 [Builtin 类型的空数组.Int1]

/* public access to _getBuiltinLogicValue() ... */
let bar = false._getBuiltinLogicValue()
print(bar.dynamicType)
/* '<<<opaque type>>>' */
/* Alt-click: 'Int1' type */

print(_getBool(bar)) // false, OK

/* construct an empty array of 'Int1':s */
func foo<T>(val: T, arr: [T] = []) -> [T] {
return arr
}
var arr = foo(bar)
print(arr.dynamicType)
/* 'Array<<<<opaque type>>>>' */
/* Alt-click: '[Int1]' type */

但是,如果我们尝试向该数组添加任何 Builtint.Int1 元素,Swift 会崩溃(运行时异常)

/* however any attempt to fill such an array (or initialize
one as none-empty) will yield a runtime exception */
//arr.append(bar) // runtime error
//let arr2 = [bar] // runtime error

Execution was interrupted, reason: EXC_BAD_ACCESS (code=1, address=0x10)

我终于在源代码中注意到了 swift/stdlib/public/core/Builtin.swift据称

// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.

这可能表明我们应该能够像上面那样使用内置类型。

最佳答案

当您调用带有前导下划线的方法时,您就不再是在调用公共(public)方法。它具有 public 属性的事实通常是由于语言限制要求它那样做。将其与 _ArrayType 进行比较,后者在技术上也是 public,但这只是因为 Swift 无法隐藏该实现细节。你仍然不应该直接使用它。他们在这些东西上加下划线是有原因的。 (我在自己的代码中遇到过这个问题。创建依赖于非公共(public)属性的协议(protocol)扩展通常很困难或不可能;当你完成时,很多事情你想成为私有(private)internal 必须是 public 否则将无法编译。)

您最初的断言“我可能不应该摆弄内置类型”目前是正确的。将来可能会提供更多内置函数。但是,您必须通过泛型来欺骗编译器甚至允许这样做,这一事实应该是您问题的答案。不。您不应该期望能够以这种方式使用内置类型。

关于swift - 隐式公共(public)访问 (Bool) 内部类型 'Builtin.Int1' : runtime exception if appending instances of 'Int1' to an array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36648890/

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