Unable to create View extension; custom view modifiers

I'm trying to create an extension to View to easily apply my custom view modifier. Below is the code for my custom viewModifier.

Code Block swift
import SwiftUI
struct AnimatableFontModifier: AnimatableModifier{
    var fontSize: CGFloat
    var animatableData: CGFloat{
        get{
            fontSize
        }
        set{
            fontSize = newValue
        }
    }
    func body(content: Content) -> some View {
        content.font(Font.system(size: fontSize))
    }
}
extension View {
    func AnimatableFontModifier(fontSize: CGFloat) -> some View{
        self.modifier(AnimatableFontModifier(fontSize: fontSize))
    }
}

This gives an error
Code Block error
Return type of instance method 'AnimatableFontModifier(fontSize:)' requires that 'some View' conform to 'ViewModifier'

But AnimatableFontModifier does confirm to the AnimatableModifier protocol, so where am I going wrong?


Answered by OOPer in 612594022
You should better avoid method names having the same name with types.
Code Block
extension View {
  func animatableFont(ofSize fontSize: CGFloat) -> some View{
        self.modifier(AnimatableFontModifier(fontSize: fontSize))
    }
}

Line 19 of your code AnimatableFontModifier(fontSize:) is calling the extension method, not the initializer of AnimatableModifier.
The issue you are having is due to the fact that you declare "AnimatableFontModifier" twice. You must change either the struct name or the func name.

See below for an example of how to update the code:
Code Block Swift
import SwiftUI
struct AnimatableFontModifier: AnimatableModifier{
  var fontSize: CGFloat
  var animatableData: CGFloat{
    get{
      fontSize
    }
    set{
      fontSize = newValue
    }
  }
  func body(content: Content) -> some View {
    content.font(Font.system(size: fontSize))
  }
}
extension View {
  func AnimatableFontModifierExtension(fontSize: CGFloat) -> some View{
    self.modifier(AnimatableFontModifier(fontSize: fontSize))
  }
}


Accepted Answer
You should better avoid method names having the same name with types.
Code Block
extension View {
  func animatableFont(ofSize fontSize: CGFloat) -> some View{
        self.modifier(AnimatableFontModifier(fontSize: fontSize))
    }
}

Line 19 of your code AnimatableFontModifier(fontSize:) is calling the extension method, not the initializer of AnimatableModifier.
Unable to create View extension; custom view modifiers
 
 
Q