Swift中带有返回类型的可选函数

Swift中带有返回类型的可选函数,swift,Swift,我确实有一个带有可选返回类型的函数。我被它的产出搞糊涂了。代码是这样的 func displayAge(age: Int) -> Int? { return 23 } if var age = displayAge(age: 22) { print("Age is correct") } else { print("Age is incorrect") } 我的年龄是22岁,我应该得到一个输出,因为年龄不正确,但我得到的年龄是正确的您似乎对这个可选的绑定if语句

我确实有一个带有可选返回类型的函数。我被它的产出搞糊涂了。代码是这样的

func displayAge(age: Int) -> Int? {
    return 23
}

if var age = displayAge(age: 22) {
    print("Age is correct")
} else {
    print("Age is incorrect")
}

我的年龄是22岁,我应该得到一个输出,因为年龄不正确,但我得到的年龄是正确的

您似乎对这个可选的绑定if语句感到困惑:

if var age = displayAge(age: 22) {
    print("Age is correct")
} else {
    print("Age is incorrect")
}
这样做的目的如下:

  • 调用
    displayAge(年龄:22)
    ,检查其返回值
  • 如果返回值不是
    nil
    • 将返回值分配给变量
      age
    • 打印(“年龄正确”)
  • 否则
    • 打印(“年龄不正确”)
它不检查
22
是否等于
23
。它将始终打印
Age是否正确
,因为
displayAge
始终返回
可选(23)
,而不是
nil

您可以检查22是否等于23,如下所示:

func displayAge() -> Int { return 23 }

if 22 == displayAge {
    print("Age is correct")
} else {
    print("Age is incorrect")
}
或者如果您真的想使用可选绑定

func displayAge(age: Int) -> Int? { return 23 == age ? 23 : nil }

if let _ = displayAge(age: 22) {
    print("Age is correct")
} else {
    print("Age is incorrect")
}

我认为你能像@Carpsen90在评论中所说的那样,更容易进入一个回击区

func displayAge(age: Int) -> Bool {

}
在函数中,您可以通过以下方式检查它是否为真:

// check if age is 23
if age == 23 {
    // then return true
    return true
} else {
    // otherwise return false
    return false
}
但要使该函数更小,您可以编写如下代码,它将返回一个布尔值,该值为true或false

// and for the code above you only need to write
return age == 23
调用函数,查看您的年龄是否正确,并获取打印或您希望在函数中使用的任何代码

if displayAge(age: 22) {
    // it's correct
    print("Age is correct")
} else {
    // otherwise incorrect
    print("Age is incorrect")
}
如果你想让这变得更容易,你可以做这样的事情:

displayAge(age: 22) ? print("Age is correct") : print("Age is incorrect")

displayAge
返回一个非可选的
23
,无论您传递的是什么数字。你能解释一下为什么你认为这是不正确的年龄,这样我们就可以确切地知道你在哪里困惑了吗?@Sweeper如果我们把年龄超过23岁,那么根据简单的if条件,它将执行第二个print语句。我不明白为什么id声明条件不起作用。你能解释一下你到底想做什么吗?不要解释代码试图做什么。解释你想要达到的目标。比如,为什么
年龄
?为什么是22岁?你想展示什么?这个时代属于什么时代?等等……如果var age=displayAge(age:22)
,你认为行
在做什么?你能解释一下你认为这行在做什么吗?我相信这就是你想要做的:
funcdisplayage(age:Int)->Bool{returnage==23};如果displayAge(年龄:22){…}
@Sweeper现在得到了它。