这个问题看起来很基本,但我试图在下面的代码中展开public class TeleportReference : MonoBehaviour {
private GameObject reference;
void Awake () {
reference = null;
}
public void SetReference(GameObject other){
reference = other;
}
public GameObject GetReference(){
return reference;
}
可选参数。我已经成功解开了可选返回,但我仍然记录了middleName
。我如何打开"马特"并删除可选的退货?
Matthew Optional("Matt") Stevenson
答案 0 :(得分:4)
您可以将nil coalescing operator用于可选的middleName
属性。如果值为nil
,则将打印默认的""
,而如果该值包含非零字符串,则会将其解包。
return ("\(name.firstName) \(name.middleName ?? "") \(name.lastName)")
但请注意,您不需要将returnFullName(..)
函数的返回类型设置为可选,因为该值永远不会为nil。
func returnFullName (name: (firstName: String, middleName: String?,
lastName: String)) -> String {
return ("\(name.firstName) \(name.middleName ?? "") \(name.lastName)")
}
print(returnFullName(("Matthew", middleName: "Matt", lastName: "Stevenson")))
// Matthew Matt Stevenson
print(returnFullName(("Matthew", middleName: nil, lastName: "Stevenson")))
// Matthew Stevenson <-- extra unwanted space
此外,我没有看到任何明显的理由在函数签名中使用元组,而不是为不同的名称组件分别使用参数。因此,另一种选择如下:
func returnFullName (firstName: String, middleName: String?,
lastName: String) -> String {
return "\(firstName) \(middleName ?? "") \(lastName)"
}
print(returnFullName("Matthew", middleName: "Matt", lastName: "Stevenson"))
// Matthew Matt Stevenson
print(returnFullName("Matthew", middleName: nil, lastName: "Stevenson"))
// Matthew Stevenson <-- extra unwanted space
最后,为避免nil
- 值middleName
的额外空间,我建议保留单行返回,而是使用带if let - else
子句的可选绑定:< / p>
func returnFullName(firstName: String, middleName: String?, lastName: String) -> String {
if let middleName = middleName {
return ("\(firstName) \(middleName) \(lastName)")
}
else {
return ("\(firstName) \(lastName)")
}
}
print(returnFullName("Matthew", middleName: "Matt", lastName: "Stevenson"))
// Matthew Matt Stevenson
print(returnFullName("Matthew", middleName: nil, lastName: "Stevenson"))
// Matthew Stevenson
现在,问题涉及展开给定示例的可选变量,现在已经很好地解决了这个问题。但是,我想我会提到你可以使用闭包和Swifts内置功能方法来压缩你的解决方案,如下所示:
// instead of a function: make use of a closure
let returnFullName : (String, String?, String) -> String = {
[$0, $1, $2].flatMap{ $0 }.joinWithSeparator(" ") }
print(returnFullName("Matthew", "Matt", "Stevenson"))
// Matthew Matt Stevenson
print(returnFullName("Matthew", nil, "Stevenson"))
// Matthew Stevenson
答案 1 :(得分:0)
您应该只传递firstName,middleName和lastName的参数,而不是使用元组。在这种特殊情况下,元组似乎是不必要的。
func returnFullName(firstName: String, middleName: String?, lastName: String) -> String?
{
if let middleName = middleName {
return ("\(firstName) \(middleName) \(lastName)")
} else {
return ("\(firstName) \(lastName)")
}
}
let fullName = returnFullName("Matthew", middleName: "Matt", lastName: "Stevenson")
if let printFullName = fullName {
print(printFullName)
}