Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a Struct appropriate for Constants

Tags:

struct

swift

When programming in Swift, what are the advantages and disadvantages for using a struct to hold all your Constants?

Normally, I would go for a class, but swift classes don't support stored type properties yet. I'd like to write my code in the form of Sample A rather in Sample B, purely because of readability, less lines of code and the single statement does what is read (a readable constant that can't be over-written).

// Sample A.swift
struct Constant {
    static let PI = 3.14
}

//Sample B.swift
private let globalPI = 3.14
class Constant {
    class var PI: Float {
        return globalPI
    }
}

If I am just referencing Constant.PI from a Struct perspective (for use in computations, printing, conditionals or whatever), am I being wasteful with the copies that are being made? Are there copies made, if I am just referencing the constant as Constant.PI in other parts of my code?

like image 439
Leo Mowry Avatar asked Nov 11 '22 01:11

Leo Mowry


1 Answers

You can declare a class constant in Swift:

class Foo {
    class var PI : Double { return 3.1416 }
}

The key is to define the custom getter and no setter.

like image 51
David Berry Avatar answered Dec 23 '22 23:12

David Berry