1

I want to do something like this in a class, but Swift doesn't allows it:

 let minDelay = Float(0.05) //Like #define minDelay 0.05 in Objective-C

 private var delay = minDelay

I get an error "Cannot use instance member minDelay within property initializer". What is the best way to correct this without initializing delay var in init or something?

2 Answers 2

3

You could use a static variable (which means there is a single instance that belongs to the type):

class MyClass {

    static let minDelay: Float = 0.05
    // You can write `Self.minDelay` starting in Swift 5.1
    private var delay = MyClass.minDelay 

}

There are a bunch of ways to approach this, but this is probably the closest to the #define you mentioned. You could also define minDelay outside of the class entirely, but I don't think that makes sense since it is only relevant to this class.

Sign up to request clarification or add additional context in comments.

4 Comments

Self.minDelay on beta :)
@Sulthan ooh! Adding to answer
@Sulthan Why would you confuse the reader with Self instead of the static class type? Self should be used when the type matters, and since this is a static variable (not class) I don't see any reason to replace Self with the static type
@J.Doe No, there is no reason to refer to the type with its name. It's about removing redundancy.
2

Swift's property initializers can't reference other properties.

struct S {
    let a = 0
    let b = a // ❌
}

error: cannot use instance member a within property initializer; property initializers run before self is available

This is one approach to trying to prevent circular definitions like this:

struct S {
    let a = b
    let b = a //❓what would these values even be?
}

Some languages like Java take a more tolerant approach, by letting a member reference any members above it (i.e. on a line above it), forming a directed acyclic graph of interconnected member definitions.

Swift takes a stricter approach, and bans it outright. To get around this, you can:

  1. Move your minDelay variable to a different place.

    • Make it a static member
    • Make it a static member of a different type (e.g. a FooConstants case-less enum).
    • Move it to a global variable (don't do this)
  2. Make it a lazy var, as you said

  3. Set its value in an initializer, where the order of assignments is explicitly expressed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.