How can I handle different types using generic type in swift?

后端 未结 2 1428
遥遥无期
遥遥无期 2021-01-23 04:08

I\'m trying to write a class which allows me to easily interpolate between two values.

class Interpolation
{
    class func interpolate(from: T, to: T,          


        
2条回答
  •  醉话见心
    2021-01-23 04:46

    It would be nice if you use Protocol to scale your generic type.

    protocol Interpolate {
        associatedtype T
        static func interpolate(from: T, to: T, progress: CGFloat) -> T
    }
    

    Then let CGRect extension conform to your protocol:

    extension CGRect: Interpolate {
        typealias T = CGRect
        static func interpolate(from: T, to: T, progress: CGFloat) -> CGRect.T {
            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
        }
    }
    
    var from = CGRect(x: 0, y: 0, width: 1, height: 1) // (0, 0, 1, 1)
    var to = CGRect(x: 1, y: 1, width: 0, height: 0)   // (1, 1, 0, 0)
    
    CGRect.interpolate(from, to: to, progress: 1)      // (1, 1, 0, 0)
    

    Also, this would make NSString conform to protocol Interpolate easily, like:

    extension NSString: Interpolate {
        typealias T = NSString
        static func interpolate(from: T, to: T, progress: CGFloat) -> NSString.T {
            //...
            return "" 
        }
    }
    

提交回复
热议问题