pointers - Swift:无法在数组中存储不安全的指针

标签 pointers swift

我创建了一个小的结构来保存版本号。

现在我搜索了一种紧凑的方法来将数字直接解析为结构体的变量。我尝试这样实现:

struct Version {
    var major: Int = 0
    var minor: Int = 0
    var revision: Int = 0

    init(string: String) {
        let components = string.componentsSeparatedByString(".")
        if 1...3 ~= components.count {
            var targets = [&major, &minor, &revision]
            for index in 0...2 {
                var scanner = NSScanner(string: components[index])
                if (!scanner.scanInteger(target[index])) {
                    major = 0
                    minor = 0
                    revision = 0
                    return                    
                }
            }
        }
    }    
}

但我收到此错误消息:

Type '[inout Int]' of variable is not materializable

我不明白这个错误。有没有办法通过这种方式实现它,使用某种指向成员变量的指针?

更新

最终我没有使用不安全指针。这是我的最终实现:

init(string: String) {
    let components = string.componentsSeparatedByString(".")
    if 1...3 ~= components.count {
        var values = [0, 0, 0]
        for index in 0..<components.count {
            var scanner = NSScanner(string: components[index])
            if (!scanner.scanInteger(&values[index])) {
                return
            }
        }
        major = values[0]
        minor = values[1]
        revision = values[2]
    }
}

最佳答案

问题是如何获得指向变量的指针。这是可能的 使用withUnsafeMutablePointers():

init(string: String) {
    let components = string.componentsSeparatedByString(".")
    if 1...3 ~= components.count {
        withUnsafeMutablePointers(&major, &minor, &revision) {
            (p1, p2, p3) -> Void in
            let targets = [p1, p2, p3]
            for index in 0...2 {
                var scanner = NSScanner(string: components[index])
                if (!scanner.scanInteger(targets[index])) {
                    self.major = 0
                    self.minor = 0
                    self.revision = 0
                    break
                }
            }
        }
    }
}

但是如果使用三个单独的情况,代码可能会更好地可读 指针数组。

关于pointers - Swift:无法在数组中存储不安全的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26300652/

相关文章:

ios - 无法在我的 iPhone 上通过 Xcode 构建 swift 项目

c++ - 何时在 C++ 中返回指针、标量和引用?

ios - 如何在 Swift 的 UITableViewCell 上添加带有点击事件的按钮?

c - 当我将指针传递给函数时出现段错误

c - 将结构指针发送到多个对话框实例的 WndProc

ios - 错误 : UICollectionView must be initialized with a non-nil layout parameter

swift - 如何在其子类中修改类的属性?

ios - "Cannot override ' init ' which has been marked unavailable"防止覆盖空 init

c - 我正在尝试使用 malloc 函数为数组分配内存,但值未正确扫描。谁能解释一下吗?

c++ - 在指针中使用 **