GO FURTHER, FASTER: Try the Swift Career Accelerator today! >>

Static member 'currency' cannot be used on protocol metatype 'SomeProtocol.Type'

Forums > SwiftUI

Hi guys, I will give you some context first. I'm trying to make a function that takes as a parameter any type that conforms to a protocol (SomeProtocol). So, I created a struct with static method called currency and this struct conforms to SomeProtocol, but, I'm getting this error when trying to pass the method as argument for that generic function: "Static member 'currency' cannot be used on protocol metatype 'SomeProtocol.Type'".

I'm just trying to recreate this SwiftUI code:

Text(20.0, format: .currency(code: Locale.current.currency?.identifier ?? "USD"))

Reading the documentation, the function from above is a generic init() that takes a generic type that conforms to some protocols.

init<F>(_ input: F.FormatInput, format: F) where F : FormatStyle, F.FormatInput : Equatable, F.FormatOutput == String

So, .currency() is a static method that comes from FloatingPointFormatStyle.Currency, a struct that conforms to FormatStyle.

My question is, why is this working in SwiftUI (passing a static method from a struct that conforms to a protocol as an argument to a function that accepts any type that conforms to that protocol) but is not in my own example:

protocol SomeProtocol {
    associatedtype SomeType: SomeProtocol
    var a: String { get }
    var b: String { get }
    static func currency(x: Int) -> SomeType
}

func someTest<T>(x: T) -> String where T: SomeProtocol{
    return "this works!"
}

struct AnotherType: SomeProtocol {
    let a = "Test"
    let b = "someTest"

    static func currency(x: Int) -> AnotherType {
        return AnotherType()
    }
}

someTest(x: .currency(x: 20))

2      

Hi!

This is a static method so it can be used only on Type level, and not as instance.

 static func currency(x: Int) -> AnotherType {
        return AnotherType()
    }

so it will work like this.

someTest(x: AnotherType.currency(x: 20))

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's all new Paywall Editor allow you to remotely configure your paywall view without any code changes or app updates.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.