Swift中未包装值的名称约定
当我在Swift中打开一个值时,我总是不确定如何命名将包含它的变量:Swift中未包装值的名称约定,swift,Swift,当我在Swift中打开一个值时,我总是不确定如何命名将包含它的变量: override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) { if let unwrappedTouches = touches { .... } } override func touchscancelled(touch:Set?,withEvent:UIEven
override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
if let unwrappedTouches = touches
{
....
}
}
override func touchscancelled(touch:Set?,withEvent:UIEvent?){
如果让展开的触摸=触摸
{
....
}
}
在Swift编码器中有一些流行的命名约定吗?您可以将与可选变量相同的名称指定给未包装变量。
首选:
var subview: UIView?
var volume: Double?
// later on...
if let subview = subview, let volume = volume {
// do something with unwrapped subview and volume
}
var optionalSubview: UIView?
var volume: Double?
if let unwrappedSubview = optionalSubview {
if let realVolume = volume {
// do something with unwrappedSubview and realVolume
}
}
非首选:
var subview: UIView?
var volume: Double?
// later on...
if let subview = subview, let volume = volume {
// do something with unwrapped subview and volume
}
var optionalSubview: UIView?
var volume: Double?
if let unwrappedSubview = optionalSubview {
if let realVolume = volume {
// do something with unwrappedSubview and realVolume
}
}
摘自。
但是,这些只是指导原则,其他约定可能也很好。也可以使用
guard let
构造来展开选项。但是,guard
创建了一个新变量,该变量将存在于else语句之外,因此与if let
构造相比,未包装变量可用的命名选项是不同的
请参阅下面的代码示例:
import Foundation
let str = Optional("Hello, Swift")
func sameName_guard() {
// 1. All Good
// This is fine since previous declaration of "str" is in a different scope
guard let str = str else {
return
}
print(str)
}
func differentName_guard() {
let str1 = Optional("Hello, Swift")
// 2. ERROR
// This generates error as str1 is in the same scope
guard let str1 = str1 else {
return
}
print(str1)
}
sameName_guard()
differentName_guard()
请不要这样做,我们终于摆脱了波兰符号。而且很难理解,当很多变量以
unwrapped
开头,而另一半变量以optional
开头时。你正在计划平衡命名,对吗?绝对不知道你可以用同一个名字!。。在Swift 1中也有可能吗?在Swift 1.2中也有可能,但我不知道Swift 1.0。同样如果var subview=subview
是,人们总是能够使用相同的名称。这会创建一个新变量,使现有变量黯然失色。由于不能在同一作用域中创建两个同名变量,因此如果在同一作用域中声明了可选变量,则在使用guard语句时不能使用相同的名称。但是,可以使用保护语句替换函数的可选参数,该语句使用函数中同名的非可选变量。