iOS Swift 4 Workout扩展报错:实例成员无法用于类型
Hey there! I totally get how confusing this error can be, especially when older Swift 3 resources don’t line up with what you’re working on. Let’s break this down simply.
What’s causing this error?
This message pops up when you mix up type-level members (things that belong to the Workout struct itself) and instance-level members (things that belong to a specific Workout object you’ve created).
- If you try to call an instance property/method using the struct name (like
Workout.distance), Swift throws this error becausedistanceonly exists on a specificWorkoutinstance, not the struct type. - Conversely, if you try to call a static member using an instance (like
myWorkout.someStaticMethod()), you’ll get a similar error.
Looking at your code
Your first extension for CustomStringConvertible is perfect—it’s an instance property (var description) that works on individual Workout instances.
The issue is in your second extension where you started typing st...—I bet you were trying to add a static member, but accidentally referenced instance properties (like distance, time, or averageHR) inside it, or vice versa.
Fix examples
Let’s cover the two most common scenarios:
Scenario 1: You want a static method to create a sample Workout
If you’re trying to add a static factory method (something you call on Workout itself), make sure you don’t reference instance properties directly—instead, create an instance inside the static method:
extension Workout { static func sampleWorkout() -> Workout { // We create a specific instance here, so we can set its properties return Workout(distance: 1500, time: 450, averageHR: 160) } } // Call it like this (using the struct type): let mySample = Workout.sampleWorkout()
Scenario 2: You want an instance method for your Workout
If you meant to add a method that works on a specific Workout instance (like calculating pace), don’t use static—just define a regular instance method that can access the instance’s properties:
extension Workout { func calculatePace() -> Double { // This works because we're inside an instance method, so we can access distance/time directly return distance / time } } // Call it like this (using an instance): let morningRun = Workout(distance: 5000, time: 1800, averageHR: 145) let pace = morningRun.calculatePace()
Quick checklist for debugging
- Check how you’re calling the member: are you using
Workout.xxx(type) orsomeWorkout.xxx(instance)? - If using the type name, the member must be marked
static(for structs) orclass(for classes). - If using an instance, the member should not be marked
static/class.
内容的提问来源于stack exchange,提问作者Caelen

