调用no参数化函数时需要一个参数swift

时间:2015-05-26 16:02:14

标签: swift parameters

我用Duncan C的帖子写了这个函数。我输入的不是参数,但在调用函数Xcode时需要一个ViewController参数。我该如何解决这个问题?

编辑:我添加了其余的代码。什么在破坏assign()函数?

主叫: calling

        import UIKit

class ViewController: UIViewController, UITextFieldDelegate {




    @IBOutlet weak var textBox: UITextView!
    @IBOutlet weak var firstInput: UITextField!
    @IBOutlet weak var resultLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        firstInput.returnKeyType = .Search
        firstInput.delegate = self
        textBox.text = ""


    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    func textFieldShouldReturn(textField: UITextField) -> Bool {
       if firstInput.text == "" {
       }
       else {
          getFromPath()

       }
        self.view.endEditing(true)
        return false
    }


    func search(#set: [String], letters: String) -> [String] {

        let result = filter(set) { item in
            for char in letters {
                if !contains(item, char) {
                    return false
                }
            }
            return true
        }

        return result
    }

    func assign(){

        let path = "/Users/ardakaraca/Documents/Xcode/ATC Radio/Stands/Stands/words.txt"
        //let bundle = NSBundle.mainBundle()
        //let path = bundle.pathForResource("words", ofType: "txt")
        let content = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
        let newArray = content!.componentsSeparatedByString("\n")




        }
         let newConten



    func getFromPath() {
        //getFromPath() func used to be in assign func.
        var letters = firstInput.text
        var res = search(set: newArray, letters: letters)
        textBox.text! = ""
        for element in res {
            textBox.text = (textBox.text ?? "") + "\n" + "\(element)"
        }

}

}

1 个答案:

答案 0 :(得分:4)

您已将assign()定义为ViewController()类的实例方法,这意味着必须在 该类的实例。

如果您尝试使用

初始化该类的属性
let dictArray = assign()

然后assign被视为

类型的“curried函数”
ViewController -> () -> [String]

解释了Xcode中意外的自动完成功能(参见 http://oleb.net/blog/2014/07/swift-instance-methods-curried-functions/)。

最简单 解决方案是将assign()函数移出 ViewController类并将其定义为“自由函数” (也许为该功能选择一个更好的名称):

import UIKit

func getWordList() -> [String] {
    let path = NSBundle.mainBundle().pathForResource("words", ofType: "txt")!
    let content = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil)
    let wordList = content!.componentsSeparatedByString("\n")
    return wordList
}

class ViewController: UIViewController {

    let wordList = getWordList()

    // ...
}