2017-03-07 133 views
0

我已經創建了我作爲constants.swift應用恆定的文件,我使用的是結構如下Swift常量文件?

struct moments { 
    struct parameter { 
     static let email = "email" 
     static let me = "me" 
     static let fields = "fields" 
     static let params = "id, name, first_name, last_name, picture.type(large), email" 
    } 

    struct title { 
     static let timeLineTitle = "Moments" 
     static let settingsTitle = "Settings" 
     static let menuTitle = "Menu" 
     static let openCamera = "Say Cheese!!! " 
     static let openGallery = "Pick from Moments " 
     static let addAudio = "Record Audio " 
     static let addNote = "Write Note " 
    } 

    struct notification { 
     static let notificationIdentifier = "NotificationIdentifier" 
    } 

    struct entity{ 
     static let image = "Image" 
     static let note = "Note" 
     static let Audio = "Audio" 
    } 

    struct menu { 
     static let home = "Home" 
     static let settings = "Settings" 
     static let logout = "Logout" 
    } 

    struct cell { 
     static let cellIdentifier = "timeLineCell" 
     static let imageCell = "imageCell" 
    } 

} 

來定義常量,但我發現多個其他選項像使用classsingletonenum我想知道哪些是在我的應用程序中使用常量的有效方式...

+1

爲了某些合乎邏輯的目的,例如爲了常量而對常量進行分組時,爲常量創建單獨的文件是有意義的。因爲它們代表相同協議中的字符串。創建常量只是爲了讓所有常量位於一個地方,使得代碼的可讀性低於在使用這些常量的文件中定義常量。 – dasblinkenlight

+0

如果常量與現有類型相關,最好創建一個擴展並在其中添加常量 – Adolfo

+0

@Adolfo您可以向我提供一個示例,瞭解如何做到這一點 –

回答

1

級和單級設計服務於不同目的常量的例子。當我們談論編寫純常量時應該排除這些內容。剩下的兩個選項是struct和enum。其中枚舉通常用於將相似類型的常量進行分組。例如,我們可能會在enum中保留一個變量的可能狀態。其他選項struct最適合您的情況,以及其他情況下我們處理純常量的情況。

1

準備常量的類和單例類不需要,直到你想要這些常量爲私有。
你可以直接在你的swift文件中創建常量,如下所示。 enter image description here

或者使用結構。

enter image description here

兩者都是創建常量的有效途徑。當你想讓常量私人化並用於指定的類時,請使用class和Singleton。
這段代碼是在swift 2.3中,它的一般想法是創建常量!

+0

如何使用枚舉按照指定[這裏](https://www.natashatherobot.com/swift-enum-no-cases/)@KiranJasvanee –

+1

讓我來創建一個答案,這也是Varun – KiranJasvanee

+0

我知道如何使用它詢問最高效率的使用和爲什麼 –

1

當你要求爲枚舉案的另一個答案。您可以在任何swift文件中創建私有/公共枚舉。
正如你在這裏看到的,我創建了兩個枚舉。 1爲我的私人用途,1爲公衆。 enter image description here

私人將不被允許在所有類中訪問。它將被允許僅在其聲明的類中被訪問。
現在我試圖訪問其他類中的枚舉,如下所示。你可以在這裏查看,我正在訪問publicEnum,但不是privateEnum。 enter image description here

現在讓我告訴你如何訪問你聲明它的類的私有枚舉。
enter image description here
您可以在這裏查看,在enum_privately類中,您可以同時訪問這兩者。現在基於上述詳細說明,您可以根據您的需求,在何時何地使用哪種方式高效地計算出它。

1

下面是關於使用與現有各類

extension Double 
{ 
    static var pi: Double 
    { 
     return 3.14159265358979323846264338327950288 
    } 
} 

print(Double.pi) 
1

對於具有特定值的常量(如字符串),Swift枚舉的問題是您不得不與原始值進行轉換。這就是爲什麼我喜歡像你一樣使用結構。

一般情況下,我認爲這是除非你需要class因特殊原因使用struct很好的做法,如果它只是保持常量有什麼優勢是使用class

將值放入單例字段看起來像是額外的工作,除非您有時需要具有不同的值,例如用於測試。