我有以下实现,但我需要分解语句,不要使用,. 重构现有代码的最佳方法是什么?
do {
let school = try schoolManager.currentSchool(), schoolName = school.name
return schoolName
} catch {
return nil
}
Run Code Online (Sandbox Code Playgroud)
由于您school除了抓取它之外并没有真正做任何事情name,因此您可以这样做:
do {
return try schoolManager.currentSchool().name
} catch {
return nil
}
Run Code Online (Sandbox Code Playgroud)
或者,甚至更简洁,因为您没有对 抛出的错误做任何事情try,您可以改为使用try?和可选链接,例如:
let school = try? schoolManager.currentSchool()
return school?.name
Run Code Online (Sandbox Code Playgroud)
或者
return (try? schoolManager.currentSchool())?.name
Run Code Online (Sandbox Code Playgroud)