Swift 原子布尔值 [英] Swift atomic boolean
问题描述
我正在尝试围绕 iOS OSTestAndSet()
和 OSTestAndClear()
函数创建一个包装器,以便与基于以下 GitHub 代码:
I'm trying to create a wrapper around the iOS OSTestAndSet()
and OSTestAndClear()
functions for use with an atomic boolean type based on the following GitHub code:
class AtomicBoolean {
private var val: Byte = 0
/// Sets the value, and returns the previous value.
/// The test/set is an atomic operation.
func testAndSet(value: Bool) -> Bool {
if value {
return OSAtomicTestAndSet(0, &val)
} else {
return OSAtomicTestAndClear(0, &val)
}
}
/// Returns the current value of the boolean.
/// The value may change before this method returns.
func test() -> Bool {
return val != 0
}
}
但是,我收到了属性声明的编译器错误,内容为:Use of undeclared type 'Byte';你的意思是使用'UInt8'吗?
However, I'm getting a compiler error for the property declaration that says: Use of undeclared type 'Byte'; did you mean to use 'UInt8'?
目前,我正在为此代码文件导入 Foundation.我已经看到其他 stackoverflow 帖子使用 Byte 类型,但我无法找到为什么在我的情况下不可用.
Currently, I'm importing Foundation for this code file. I've seen other stackoverflow posts use the Byte type but I haven't been able to find why this isn't available in my case.
我正在使用以下版本的 Swift:Apple Swift 1.2 版 (swiftlang-602.0.53.1 clang-602.0.53)
I'm using the following version of Swift: Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)
此外,如果我按照编译器的建议将数据类型更改为 UInt8,我会在 OSAtomicTestAndSet() 和 OSAtomicTestAndClear() 调用中收到其他错误,说明以下内容:无法分配给类型为UInt8"的不可变值
尽管我使用的是 var
声明而不是 let
.
Furthermore, if I change the datatype to UInt8 as the compiler suggests, I receive additional errors on the OSAtomicTestAndSet() and OSAtomicTestAndClear() calls that states the following: Cannot assign to immutable value of type 'UInt8'
despite the fact that I'm using a var
declaration and not a let
.
推荐答案
Byte
到 UInt8
的 typealias
被移除,不再存在在 Swift 1.2 中.您可以自己定义它,也可以使用 UInt8
(更好的选择).
The typealias
of Byte
to UInt8
was removed and no longer exists in Swift 1.2. You can define it yourself, or just use UInt8
(the better option).
在评论中,您说不可变的问题是您使用的是 struct
而不是 class
.您可以使用struct
,您只需要将关键字mutating
添加到任何修改struct
的函数中:
In the comments, you said the immutable problem was that you are using a struct
instead of a class
. You can use struct
, you just have to add the keyword mutating
to any function that modifies the struct
:
typealias Byte = UInt8
struct AtomicBoolean {
private var val: Byte = 0
/// Sets the value, and returns the previous value.
/// The test/set is an atomic operation.
mutating func testAndSet(value: Bool) -> Bool {
if value {
return OSAtomicTestAndSet(0, &val)
} else {
return OSAtomicTestAndClear(0, &val)
}
}
/// Returns the current value of the boolean.
/// The value may change before this method returns.
func test() -> Bool {
return val != 0
}
}
这篇关于Swift 原子布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!