Swift:无法在阵列中存储不安全的指针

时间:2014-10-10 13:30:45

标签: pointers swift

我创建了一个小struct来保存版本号。

现在我搜索了一种简洁的方法来将数字直接解析为结构的变量。我试着用这种方式实现它:

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]
    }
}

2 个答案:

答案 0 :(得分:3)

问题是如何获取指向变量的指针。 是可能的 使用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
                }
            }
        }
    }
}

但代码可能会更好地读取三个单独的案例 一个指针数组。

答案 1 :(得分:0)

in-out不是UnsafePointer也不是UnsafeMutablePointer,只有当函数接受Unsafe???Pointer<T>族参数时,输入输出表达式才会作为相应的指针类型传递。见:the docs

试试这个:

var targets:[Int] = [0,0,0];
for index in 0...2 {
    var scanner = NSScanner(string: components[index])
    if (!scanner.scanInteger(&targets[index])) {
        major = 0
        minor = 0
        revision = 0
        return
    }
}
major = targets[0]
minor = targets[1]
revision = targets[2]

OR

var targets:[UnsafeMutablePointer<Int>] = []
targets.append(&major)
targets.append(&minor)
targets.append(&revision)
for index in 0...2 {
    var scanner = NSScanner(string: components[index])
    if (!scanner.scanInteger(targets[index])) {
        major = 0
        minor = 0
        revision = 0
        return
    }
}