命名 Naming
不建議使用系統內建的關鍵字來命名變數、常數、函式、類別及其他自定義的型別,如果真的一定要使用的話,必須以一對反引號`````把名稱包起來,如下:
// 無法這樣命名 這行會報錯誤
let class = 20
// 必須以一對反引號 ` 包起名稱
var `class` = 12
// 使用也必須加上反引號
print("It is \(`class`)")
對於類別Class、方法Method、變數Variable、函式Function等使用帶駝峰式的描述性名稱。類別名稱應大寫,而方法名稱和變數應以小寫字母開頭。
大駝峰式命名 UpperCamelCase
- 類別 ClassName
- 列舉 EnumName
- 結構 StructName
- 擴展 ExtensionsName
- 協定 ProtocolName
小駝峰式命名 lowerCamelCase
- 方法 methodsName
- 函式 functionName
- 變數 variablesName
- 屬性 propertyName
private let maximumWidgetCount = 100
class WidgetContainer {
var widgetButton: UIButton
let widgetHeightPercentage = 0.85
func countBMIFromWidget(_ widget: Float, height: Float)
}
Object 元件名稱結尾處加上元件型別
let cancelButton: UIButton
let titleLabel: UILabel
let previewImage: UIImage
Function 函式參數的一致標記特性
必須明確指定第一個參數的標記,並注意命名方式使它更易讀,並以動詞+名詞,可以"_"省略
// 建議
func walk(from startCity: String, to endCity: String) {
print("Tom walked from \(startCity) to \(endCity)")
}
//在呼叫的時候,就可以寫成:
walk(from: "Taipei", to: "Tainan")
// 省略
func walk(_ startCity: String, _ endCity: String) {
print("Tom walked from \(startCity) to \(endCity)")
}
// would be called like this:
walk("Taipei", "Tainan")
列舉 Enum
- EnumName
- variablesName
public enum UIButtonType : Int {
case custom // no button type
@available(iOS 7.0, *)
case system // standard system button
case detailDisclosure
case infoLight
case infoDark
case contactAdd
public static var roundedRect: UIButtonType { get } // Deprecated, use UIButtonTypeSystem instead
}
常數
全域:駝峰式命名,且在開頭加上小寫"k"
區域:小駝峰式命名
static:全大寫,字母間使用下底線" _ "隔開,且完整敘述constants代表的意義(color, image, sound)
import UIKit
// Color
struct ColorPalette {
static let Red = UIColor(red: 1.0, green: 0.1491, blue: 0.0, alpha: 1.0)
static let Green = UIColor(red: 0.0, green: 0.5628, blue: 0.3188, alpha: 1.0)
static let Blue = UIColor(red: 0.0, green: 0.3285, blue: 0.5749, alpha: 1.0)
struct Gray {
static let Light = UIColor(white: 0.8374, alpha: 1.0)
static let Medium = UIColor(white: 0.4756, alpha: 1.0)
static let Dark = UIColor(white: 0.2605, alpha: 1.0)
}
}
// Image
static let IMAGE_NAVIGATIONBAR_BG_BLUE = "header_bg_1monitor.png"
// Sound
static let SOUND_NOTIFICATION_BEE = "notification_bee.mp3"
let kMaxNumberOfImages = 10;
let kMaxNumberOfVideos = 1;
let kViewsTransparency = 0.6;
let kTickImageName = "camera_select_multiple";
let kDownArrowName = "camera_arrowdown";
let kUpArrowName = "camera_arrowup"
class OverlayView: UIView {
func loadPhotosInCollectionView() {
var tempAssets = [PHAsset]();
var tempThumbnails = [BAMedia]();
let result = PHAssetCollection.fetchMoments(with: nil);
}
}