Swift Scope -从函数返回if和for结果



我如何从这里的函数返回i的结果?我可以从if{}内部返回它,但然后我得到一个错误,没有全局返回(对于函数)。我的目标是编写一个接受整数并返回其平方根的函数。我的下一步是抛出一个错误,如果它不是Int或1和10,000之间,但请假设简单的数字对于这个问题。

let userInputInteger = 9
func squareRootCheckpoint4(userInputInteger: Int) -> Int {
for i in 1...100 {
let userInputInteger = i * i
if i == userInputInteger {
break
}
}
return i
}

更新:为了能够返回它,你必须在for循环外声明一个变量,然后根据逻辑赋值&;i&;与外部变量相反

func squareRootCheckpoint4(userInputInteger: Int) -> Int {
var result = 0 // this is to keep the result
for i in 1...100 {
let powerOfTwoResult = i * i
if powerOfTwoResult == userInputInteger {
result = i // assign result variable based on the logic
break
}
}
return result // return result
}

显示的错误是因为如果for循环结束而没有击中if语句,则函数将无法返回任何Int。这就是为什么编译器会生成&;no global return&;错误。

如果不想返回默认值,一种方法是抛出错误。可以从函数抛出错误(https://docs.swift.org/swift-book/LanguageGuide/ErrorHandling.html)。例如,如果您的目标是返回整数的平方根,并在输入整数不在1到10000之间时抛出错误(如果我理解正确的话),您可以这样做

enum InputError: Error {
case invalidInteger
}
func squareRootCheckpoint4(userInputInteger: Int) throws -> Int {
if userInputInteger < 1 || userInputInteger > 10000 {
throw InputError.invalidInteger
}

// calculate square root
return resultOfSquareroot
}
// and to handle the error, you could encapsulate the squareRootCheckpoint4 function in a do-catch statement
do {
let squareRootResult = try squareRootCheckpoint4(userInputInteger: 4)
} catch InputError.invalidInteger {
// handle your error here
}

或者,您可以在调用squarerootcheckpoin4函数之前单独对输入整数进行验证。例如

func validate(_ input: Int) -> Bool {
if userInputInteger < 1 || userInputInteger > 10000 {
return false
}
return true
}
func squareRootCheckpoint4(userInputInteger: Int) -> Int {
// calculate square root
return resultOfSquareroot
}
var input: Int = 9
if validate(input) {
let squareRootResult = squareRootCheckpoint4(input)
} else {
// handle when input is invalid
}

交换了一些东西,并且需要从函数返回一些东西(任何东西)。问题的框架只允许在输入不是带平方根的整数时不工作的解决方案。

细节列表:

  • 函数参数名称userInputInteger不应该被用来实例化一个新对象。这是令人困惑的。我这样做是因为我正在学习,认为这是必要的。
  • 应该将i乘以i(或i的平方)赋值给一个新对象。
  • if语句应该等于这个新对象,而不是i
  • 函数应该返回一些东西。当iif语句中返回时,它在for循环之外的任何地方都不可用。代码示例中的print语句有助于解释在这些不同作用域中可用的内容以及不可用的内容。
  • i返回时,for循环停止。当猜测(i)等于输入(userInputInteger)时,就会发生这种情况。
  • 如果输入没有平方根,for循环将持续到100。
  • 函数应该返回if语句试图猜测的正确数字,但是您必须告诉它(使用return语句)并在正确的位置执行。这是"全局返回"。错误。但是,由于问题中的这种方法设置得很差,没有错误处理,因此只有具有平方根的Integer才能正确返回。在这种情况下,函数的全局返回无关紧要;Swift只是要求返回一些东西,不管它是否被使用。

代码示例-直接回答:

import Cocoa
let userInputInteger = 25
let doesNotMatter = 0
print("sqrt((userInputInteger)) is (sqrt(25))") //correct answer for reference

func squareRootCheckpoint4(userInputInteger2: Int) -> Int {
var j: Int
for i in 1...100 {
print("Starting Loop (i)")
j = i * i
if j == userInputInteger2 {

print("i if-loop (i)")
print("j if-loop (j)")
return i
}
print("i for-loop (i)")
print("j for-loop (j)")
}
//print("i func-end (i)") //not in scope
//print("j func-end (j)") //not in scope
//return i                 //not in scope
//return j                 //not in scope
print("Nothing prints here")

// but something must be returned here
return doesNotMatter
}
print("Input was (userInputInteger)")
print("The Square Root of (userInputInteger) is (squareRootCheckpoint4(userInputInteger2: userInputInteger))")

代码示例-改进错误处理

import Cocoa
enum ErrorMsg : Error {
case outOfBoundsError, noRootError
}
func checkSquareRoot (Input userInputInteger2: Int) throws -> Int {
if userInputInteger < 1 || userInputInteger > 10_000 {
throw ErrorMsg.outOfBoundsError
}

var j : Int
for i in 1...100 {
print("Starting Loop (i)")
j = i * i
if j == userInputInteger2 {
print("i if-loop (i)")
print("j if-loop (j)")
return i
}
print("i for-loop (i)")
print("j for-loop (j)")
}
throw ErrorMsg.noRootError
}
let userInputInteger = 25
print("Input was (userInputInteger)")
do {
let result = try checkSquareRoot(Input: userInputInteger)
print("The Square Root of (userInputInteger) is (result)")
} catch ErrorMsg.outOfBoundsError {
print("out of bounds: the userInputInteger is less than 1 or greater than 10,000")
} catch ErrorMsg.noRootError {
print("no root")
}
print("Swift built-in function for reference: sqrt((userInputInteger)) is (sqrt(25))") //correct answer for reference

最新更新