gpt4 book ai didi

ios - 有没有办法在 Swift 中满足某个条件时结束递归方法?

转载 作者:行者123 更新时间:2023-11-28 10:13:59 26 4
gpt4 key购买 nike

我有一个函数,它返回一个值及其大小,可以根据计算标签宽度设置。满足某些条件后,我想停止递归函数的进一步过程,如 break

func getLength(value: Int, font: UIFont, viewFrame: CGRect) -> (width:CGFloat, text:String) {
let width: CGFloat!
var val = value

let size = String(format:"%d",value).size(attributes: [NSFontAttributeName: font])
if size.width+10 > viewFrame.size.width {
width = viewFrame.size.width-10
val = val/10
_ = getLength(value: val, font: font, viewFrame: viewFrame)
return (0.0 , "")

} else {
width = size.width+10
return (width,String(format:"%d+",val))
}
}

最佳答案

当使用递归函数时,你应该在两种情况下都返回值

 func getLength(value: Int, font: UIFont, viewFrame: CGRect) -> (width:CGFloat, text:String) {
let width: CGFloat!
var val = value

let size = String(format:"%d",value).size(attributes: [NSFontAttributeName: font])
if size.width+10 > viewFrame.size.width {
width = viewFrame.size.width-10
val = val/10
return getLength(value: val, font: font, viewFrame: viewFrame)

} else {
width = size.width+10
return (width,String(format:"%d+",val))
}
}

关于ios - 有没有办法在 Swift 中满足某个条件时结束递归方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43845979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com