草庐IT

swift - 调用无参数函数时需要参数 swift

coder 2023-09-13 原文

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

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

调用:

        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)"
        }

}

}

最佳答案

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

如果您尝试使用初始化该类的属性

let dictArray = assign()

然后 assign 被当作类型的“柯里化(Currying)函数”

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()

    // ...
}

关于swift - 调用无参数函数时需要参数 swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30463549/

有关swift - 调用无参数函数时需要参数 swift的更多相关文章

  1. ruby - 我需要将 Bundler 本身添加到 Gemfile 中吗? - 2

    当我使用Bundler时,是否需要在我的Gemfile中将其列为依赖项?毕竟,我的代码中有些地方需要它。例如,当我进行Bundler设置时:require"bundler/setup" 最佳答案 没有。您可以尝试,但首先您必须用鞋带将自己抬离地面。 关于ruby-我需要将Bundler本身添加到Gemfile中吗?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/4758609/

  2. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  3. ruby - RSpec - 使用测试替身作为 block 参数 - 2

    我有一些Ruby代码,如下所示:Something.createdo|x|x.foo=barend我想编写一个测试,它使用double代替block参数x,这样我就可以调用:x_double.should_receive(:foo).with("whatever").这可能吗? 最佳答案 specify'something'dox=doublex.should_receive(:foo=).with("whatever")Something.should_receive(:create).and_yield(x)#callthere

  4. ruby - rspec 需要 .rspec 文件中的 spec_helper - 2

    我注意到像bundler这样的项目在每个specfile中执行requirespec_helper我还注意到rspec使用选项--require,它允许您在引导rspec时要求一个文件。您还可以将其添加到.rspec文件中,因此只要您运行不带参数的rspec就会添加它。使用上述方法有什么缺点可以解释为什么像bundler这样的项目选择在每个规范文件中都需要spec_helper吗? 最佳答案 我不在Bundler上工作,所以我不能直接谈论他们的做法。并非所有项目都checkin.rspec文件。原因是这个文件,通常按照当前的惯例,只

  5. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  6. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  7. ruby - 检查方法参数的类型 - 2

    我不确定传递给方法的对象的类型是否正确。我可能会将一个字符串传递给一个只能处理整数的函数。某种运行时保证怎么样?我看不到比以下更好的选择:defsomeFixNumMangler(input)raise"wrongtype:integerrequired"unlessinput.class==FixNumother_stuffend有更好的选择吗? 最佳答案 使用Kernel#Integer在使用之前转换输入的方法。当无法以任何合理的方式将输入转换为整数时,它将引发ArgumentError。defmy_method(number)

  8. ruby - 如何在 Lion 上安装 Xcode 4.6,需要用 RVM 升级 ruby - 2

    我实际上是在尝试使用RVM在我的OSX10.7.5上更新ruby,并在输入以下命令后:rvminstallruby我得到了以下回复:Searchingforbinaryrubies,thismighttakesometime.Checkingrequirementsforosx.Installingrequirementsforosx.Updatingsystem.......Errorrunning'requirements_osx_brew_update_systemruby-2.0.0-p247',pleaseread/Users/username/.rvm/log/138121

  9. ruby-on-rails - 在默认方法参数中使用 .reverse_merge 或 .merge - 2

    两者都可以defsetup(options={})options.reverse_merge:size=>25,:velocity=>10end和defsetup(options={}){:size=>25,:velocity=>10}.merge(options)end在方法的参数中分配默认值。问题是:哪个更好?您更愿意使用哪一个?在性能、代码可读性或其他方面有什么不同吗?编辑:我无意中添加了bang(!)...并不是要询问nobang方法与bang方法之间的区别 最佳答案 我倾向于使用reverse_merge方法:option

  10. ruby-on-rails - 在 ruby​​ 中使用 gsub 函数替换单词 - 2

    我正在尝试用ruby​​中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了

随机推荐