在这里它说:"注意:_意思是"我不关心那个价值",但是来自JavaScript,我不明白这意味着什么.
我能够打印这些函数的唯一方法是在参数之前使用下划线:
func divmod(_ a: Int, _ b:Int) -> (Int, Int) {
return (a / b, a % b)
}
print(divmod(7, 3))
print(divmod(5, 2))
print(divmod(12,4))
Run Code Online (Sandbox Code Playgroud)
如果没有下划线,我必须这样写它以避免任何错误:
func divmod(a: Int, b:Int) -> (Int, Int) {
return (a / b, a % b)
}
print(divmod(a: 7, b: 3))
print(divmod(a: 5, b: 2))
print(divmod(a: 12,b: 4))
Run Code Online (Sandbox Code Playgroud)
我不明白这个下划线用法.何时,如何以及为何使用这些下划线?
func say(name:String, msg:String) {
println("\(name) say \(msg)")
}
say("Henry","Hi,Swift") <---- error because missing argument label 'msg' in call
Run Code Online (Sandbox Code Playgroud)
我需要用
say("Henry",msg:"Hi,Swift")
Run Code Online (Sandbox Code Playgroud)
为什么?如果我在func中放入两个以上的var,这样当我调用这个函数时我需要编写var name而不是first var
它真的很麻烦,我在iBook Swift教程中没有看到任何解释.
单独的下划线在函数定义中意味着什么?
例如 map(_:)
我明白在定义函数时我可以做到:
func myFunc(_ string: String) { ... }
Run Code Online (Sandbox Code Playgroud)
我是否会将其称为myFunc(_:)而不是myFunc(_string:),即故意隐藏参数名称?
使用是否let _ = ...有任何目的?
我在Swift References中看到了什么是_下划线代表的问题和答案?我知道下划线可以用来表示不需要的变量.
如果我只需要一个元组的值,就像上面链接中的示例一样,这是有意义的:
let (result, _) = someFunctionThatReturnsATuple()
Run Code Online (Sandbox Code Playgroud)
但是,我最近遇到了这个代码:
do {
let _ = try DB.run( table.create(ifNotExists: true) {t in
t.column(teamId, primaryKey: true)
t.column(city)
t.column(nickName)
t.column(abbreviation)
})
} catch _ {
// Error throw if table already exists
}
Run Code Online (Sandbox Code Playgroud)
如果我删除了,我不会收到任何编译器警告或错误let _ =.在我看来,这样更简单,更易读.
try DB.run( table.create(ifNotExists: true) {t in
t.column(teamId, primaryKey: true)
t.column(city)
t.column(nickName)
t.column(abbreviation)
})
Run Code Online (Sandbox Code Playgroud)
该代码的作者撰写了一本关于Swift的书和博客.我知道作者不是绝对正确的,但它让我想知道是否有我遗失的东西.
我使用mapSwift中的函数迭代一堆子视图并从superview中删除它们.
self.buttons.map { $0.removeFromSuperview() }
Run Code Online (Sandbox Code Playgroud)
当我从Swift 1.x升级到2.0时,Xcode发出警告,表示地图的返回值未使用.所以我分配了它,let x = ...我得到另一个警告:
所以我让Xcode为我修复警告,它给了我这个:
_ = self.buttons.map { $0.removeFromSuperview() }
不在方法参数的上下文中,下划线的意义是什么?这是什么意思?
编辑:
我知道当一个方法参数是匿名的时,下划线取而代之.我正在谈论方法中间的下划线.它不是信息的一部分.
在阅读Swift的文档时,Apple通常使用functionName(_:name:)或类似的东西.这个模式究竟是什么,有时候_:_:,有时只是_:,和_:name:.我认为它与参数简写有关,但我不确定,也无法在Swift的编程指南中找到解释.谢谢!
例:
insert(_:atIndex:)
Run Code Online (Sandbox Code Playgroud) 在下面的示例代码中,如果删除webViewDidFinishLoad声明中的下划线,则不会触发.下划线做什么?
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet weak var playerWebView: UIWebView!
let youtubeUrl = URL(string: "https://youtube.com")
override func viewDidLoad() {
super.viewDidLoad()
playerWebView.delegate = self
let request = URLRequest(url: youtubeUrl!)
playerWebView.loadRequest(request)
print("viewDidLoad")
}
func webViewDidFinishLoad(_ playerWebView: UIWebView) {
print("webviewFinishedLoad")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Run Code Online (Sandbox Code Playgroud)