【问题标题】:Why Cannot find 'newArray' in scope when using return outside of if statement为什么在if语句之外使用return时在范围内找不到'newArray'
【发布时间】:2021-05-20 00:51:39
【问题描述】:
import Foundation

func aVeryBigSum(ar: [Int]) -> Int {

    if ar[0] < ar[1]{
    
        var newArray = 1
        
    } else if ar[0] > ar[1[]{
        var newArray = 0
    }
    
    return newArray
}


print(aVeryBigSum(ar: [5,8]))

【问题讨论】:

    标签: swift if-statement return


    【解决方案1】:

    您在ifelse 语句中创建了不同的newArrays。并且您不能使用超出其范围的属性。所以只需在ifelse 语句中返回一个值。或者像第二个例子一样在函数作用域(不是 if-else 语句的作用域)中创建newArray


    第一

    func aVeryBigSum(ar: [Int]) -> Int {
    
      if ar[0] < ar[1] {
        return 1
      } else {
        return 0
      }
    }
    

    第二

    func aVeryBigSum(ar: [Int]) -> Int {
      let newArray: Int
    
      if ar[0] < ar[1] {
        newArray = 1
      } else {
        newArray = 0
      }
      return newArray
    }
    

    Scope & Context Explained In Swift

    【讨论】:

    • 如果我这样做了,我会收到一个错误“预期返回'Int'的函数中缺少返回
    • 你是对的,请检查我更新的答案。 @BabyProgrammer 您能否将其标记为已接受其他福利?
    • 谢谢 emrcftci,我刚刚打了绿勾。我目前正在阅读您提供的范围和上下文链接。很高兴你的帮助,我已经坚持了好几个小时了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-28
    • 2011-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多