Swift 3.0呼叫结果未使用

Ary*_*yap 143 ios swift swift3

我在swift 3.0中写作

我有这个代码,它给我警告结果,呼叫未使用

        public override init(){
            super.init()
        }

        public init(annotations: [MKAnnotation]){
            super.init()
            addAnnotations(annotations:  annotations)

        }

        public func setAnnotations(annotations:[MKAnnotation]){
            tree = nil
            addAnnotations(annotations: annotations)
        }

        public func addAnnotations(annotations:[MKAnnotation]){
            if tree == nil {
                tree = AKQuadTree()
            }

            lock.lock()
            for annotation in annotations {
    // The warning occurs at this line
         tree!.insertAnnotation(annotation: annotation)
            }
            lock.unlock()
        }
Run Code Online (Sandbox Code Playgroud)

我已经尝试在另一个类中使用此方法,但它仍然给我错误,insertAnnotation的代码在上面

func insertAnnotation(annotation:MKAnnotation) -> Bool {
        return insertAnnotation(annotation: annotation, toNode:rootNode!)
    }

    func insertAnnotation(annotation:MKAnnotation, toNode node:AKQuadTreeNode) -> Bool {

        if !AKQuadTreeNode.AKBoundingBoxContainsCoordinate(box: node.boundingBox!, coordinate: annotation.coordinate) {
            return false
        }

        if node.count < nodeCapacity {
            node.annotations.append(annotation)
            node.count += 1
            return true
        }

        if node.isLeaf() {
            node.subdivide()
        }

        if insertAnnotation(annotation: annotation, toNode:node.northEast!) {
            return true
        }

        if insertAnnotation(annotation: annotation, toNode:node.northWest!) {
            return true
        }

        if insertAnnotation(annotation: annotation, toNode:node.southEast!) {
            return true
        }

        if insertAnnotation(annotation: annotation, toNode:node.southWest!) {
            return true
        }


        return false

    }
Run Code Online (Sandbox Code Playgroud)

我已经尝试了很多方法,但只是不起作用,但在swift 2.2它可以正常任何想法为什么会发生这种情况?

Dav*_*ndz 440

您遇到此问题,因为您正在调用的函数返回一个值,但您忽略了结果.

有两种方法可以解决此问题:

  1. 通过_ =在函数调用前添加来忽略结果

  2. 添加@discardableResult到函数的声明以使编译器静音

  • 太好了!我喜欢"@discardableResult"解决方案. (123认同)
  • 太好了!我喜欢"_ ="解决方案. (27认同)
  • 谁为Swift决定了这种行为!?我想用一些编译器选项来抑制这个警告,它非常烦人且没用. (8认同)
  • 一方面你可以把`@ discardableResult`放一次并修复它们,但另一方面你无法使用你的pod,所以你必须使用第一个解决方案. (6认同)
  • @gran_profaci您可能正在使用其他人的代码(通过Pods或其他地方),并且无法更改代码接口定义,在这种情况下,“ _ =”是唯一的解决方案。 (2认同)