gpt4 book ai didi

swift - 我如何编写一个函数,它接受泛型类型参数,但根据泛型对象的类型返回不同的类型?

转载 作者:行者123 更新时间:2023-11-28 12:43:50 24 4
gpt4 key购买 nike

<分区>

我正在尝试在 swift3 中编写一个基本的插值函数。不过,我遇到了很多错误。这显然不是泛型的正确使用方式,但也许我对它们的应用存在根本性的误解?

class func interpolate<T>(from: T, to: T, progress: CGFloat) -> T
{
// Safety
assert(progress >= 0 && progress <= 1, "Invalid progress value: \(progress)")

if let from = from as? CGFloat, let to = to as? CGFloat
{
return from + (to - from) * progress // No + candidates produce the expected contextual result type 'T'
}
if let from = from as? CGPoint, let to = to as? CGPoint
{
var returnPoint = CGPoint()
returnPoint.x = from.x + (to.x-from.x) * progress
returnPoint.y = from.y + (to.y-from.y) * progress
return returnPoint // Cannot convert return expression of type 'CGPoint' to return type 'T'
}
if let from = from as? CGRect, let to = to as? CGRect
{
var returnRect = CGRect()
returnRect.origin.x = from.origin.x + (to.origin.x-from.origin.x) * progress
returnRect.origin.y = from.origin.y + (to.origin.y-from.origin.y) * progress
returnRect.size.width = from.size.width + (to.size.width-from.size.width) * progress
returnRect.size.height = from.size.height + (to.size.height-from.size.height) * progress
return returnRect // Cannot convert return expression of type 'CGRect' to return type 'T'
}

return nil // Nil is incompatible with return type 'T'
}

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