func addSublayersAnimationNeedReverse(anim : CAAnimation, key : String, layer : CALayer, reverseAnimation : Bool, totalDuration : CFTimeInterval){
let sublayers = layer.sublayers
let sublayersCount = sublayers!.count

let setBeginTime =
{
(subAnim:CAAnimation, sublayerIdx:NSInteger) -> Void  in

if let instDelay = (subAnim.value(forKey: "instanceDelay") as? NSNumber)?.floatValue{
if (instDelay != 0) {
let instanceDelay = CGFloat(instDelay)
let orderType : NSInteger = ((subAnim.value(forKey: "instanceOrder")!) as AnyObject).integerValue
switch (orderType) {
case 0: subAnim.beginTime = CFTimeInterval(CGFloat(subAnim.beginTime) + CGFloat(sublayerIdx) * instanceDelay)
case 1: subAnim.beginTime = CFTimeInterval(CGFloat(subAnim.beginTime) + CGFloat(sublayersCount - sublayerIdx - 1) * instanceDelay)
case 2:
let middleIdx     = sublayersCount/2
let begin         = CGFloat(abs(middleIdx - sublayerIdx)) * instanceDelay
subAnim.beginTime += CFTimeInterval(begin)

case 3:
let middleIdx     = sublayersCount/2
let begin         = CGFloat(middleIdx - abs((middleIdx - sublayerIdx))) * instanceDelay
subAnim.beginTime     += CFTimeInterval(begin)

default:
break
}
}
}
}

for (idx, sublayer) in sublayers!.enumerated() {

if let groupAnim = anim.copy() as? CAAnimationGroup{
var newSubAnimations : [CAAnimation] = []
for subAnim in groupAnim.animations!{
newSubAnimations.append(subAnim.copy() as! CAAnimation)
}
groupAnim.animations = newSubAnimations
let animations = groupAnim.animations
for sub in animations! as [CAAnimation]{
setBeginTime(sub, idx)
//Reverse animation if needed
if reverseAnimation {
_ = self.reverseAnimation(anim: sub, totalDuration: totalDuration)
}

}
sublayer.add(groupAnim, forKey: key)
}
else{
let copiedAnim = anim.copy() as! CAAnimation
setBeginTime(copiedAnim, idx)
sublayer.add(copiedAnim, forKey: key)
}

}
}
