函数的未解析标识符的使用// Swift

时间:2018-02-10 21:56:05

标签: swift

更新

我目前正在我的大学学习Swift课程,并且正在努力学习。我以为我清楚地遵循了说明,但是我收到了关于“使用未解析的标识符”的错误。

这是完整的错误:

错误:我的函数Playground 2 2.playground:23:8:错误:使用未解析的标识符'newGPA' 切换newGPA {

这是我的代码(原始说明如下):

var gpa: Int
var attemptedHours: Int
var earnedGradePoints: Int

// create your function here
func gpaUpdater(hours moreHours: Int, grade moreGPA: Int) {
    let _: Int = attemptedHours + moreHours
    let newGPA: Int = gpa + moreGPA
    print(newGPA)
}

// call the function
gpaUpdater(hours: 16, grade: 60)

// add the new hours and grade points here and call the function again
switch newGPA {
case 0...1.8:
    print("You will be placed on suspension")
case 1.8...2.0:
    print("You will be placed on probation")
case 3.5...3.8:
    print("You will be put on the dean's list.")
case 3.9:
    print("You will be put on the president's list.")
default:
    print("Carry on. Nothing to see here.")
}

说明:

我们将从一个学期到下一个学期跟踪您的GPA。假设在二年级结束时,你已经尝试了60个小时,并且获得了222.5个分。将尝试的小时数和成绩点分配给变量。编写一个更新当前GPA并将其分配给GPA var的函数(您将在此过程中更新它)。标记您的函数参数。从函数中打印新的GPA。

在本学期结束时,为您的记录添加16小时和60个成绩点。调用gpa函数来更新整体gpa。

在年底测试你的gpa,看看是否需要采取任何行政措施。如果gpa小于1.8,学生将需要被暂停。如果小于2.0,我们需要让学生接受缓刑。如果超过3.5,我们会把学生放在院长名单上,如果超过3.9,我们会把学生放在校长名单上。创建一个打印建议的管理操作的开关。如果不需要采取任何措施,请打印“继续。没有什么可看的。”为参数创建内部和外部标签。

感谢您的帮助!

更新

我的Swift代码的功能部分现在是正确的,谢谢大家的帮助。现在我正在尝试修复我的switch语句。这是我的代码:

// add the new hours and grade points here and call the function again
switch gpa {
case gpa > 1.8:
    print("You will be placed on suspension")
case 1.8...2.0:
    print("You will be placed on probation")
case 3.5...3.8:
    print("You will be put on the dean's list.")
case gpa > 3.9:
    print("You will be put on the president's list.")
default:
    print("Carry on. Nothing to see here.")
}

我认为问题在于,我的老师希望GPA成为一个int,但是如果我想为gpa使用1.9之类的值,那么它需要是双倍的。这是我得到的错误:

error: My Functions Playground 2 2.playground:26:10: error: binary operator '>' cannot be applied to operands of type 'Int' and 'Double' case gpa > 1.8

2 个答案:

答案 0 :(得分:1)

范围。范围。范围。

newGPAgpaUpdater范围内在本地声明。它在顶层不可见。

你可以做到

// create your function here
func gpaUpdater(hours moreHours: Int, grade moreGPA: Int) -> Int {
    // let _: Int = attemptedHours + moreHours
    return gpa + moreGPA
}

// call the function
let newGPA = gpaUpdater(hours: 16, grade: 60)

// add the new hours and grade points here and call the function again
switch newGPA { ...

gpaUpdater的(未使用的)第一个参数以及切换Int

的浮点情况没有评论

答案 1 :(得分:-1)

我将从任务角度回答这个问题;关于返回局部变量值的其他答案对于访问newGPA变量是正确的。

通过创建" newGPA"错过了作业中的重点。变量。作业声明为"更新"具有函数内新值的全局gpa变量。

如果这是介绍性编码,您可能没有遇到递归的概念。这基本上是通过将自己包含在计算中来分配一些值。

而不是

let newGPA: Int = gpa + moreGPA print(newGPA)

想想

gpa = gpa + moreGPA
print(gpa)

也可以写成

gpa += moreGPA

然后在你的开关功能中使用gpa。

这样做是将您的全局gpa变量更新为新值(通过向其添加更多GPA)。这是全局变量的主要优势之一。可以从程序中的任何位置访问和修改它。

这是基于作业指示的理解。也就是说,从函数中返回一个值更清晰(在我看来),因为全局变量可能会在更复杂的程序中出现冲突。

相关问题