一、Apple 官方格式規範的核心原則

Apple 對代碼格式的要求核心是:可讀性優先、風格統一、簡潔不冗餘,所有規範都圍繞這三個原則展開,以下分 Swift 和 Objective-C 兩大語言詳細説明。


二、Swift 官方格式規範(重點)

Apple 在 Swift.org 和 Xcode 內置的格式化工具中定義了核心規範,以下是必須遵守的關鍵項:

1. 縮進與空格

  • 縮進:使用4 個空格(禁止用 Tab),Xcode 默認已配置(可在 Xcode > Settings > Text Editing > Indentation 中確認);
  • 二元運算符兩側:必須加 1 個空格(+/-/*/=/==等),示例:

    swift
// 錯誤(無空格)
let sum=a+b*c
if a==b{...}
// 正確(Apple規範)
let sum = a + b * c
if a == b { ... }
  • 逗號後:必須加 1 個空格,示例:
    swift
// 錯誤
let array = [1,2,3]
func test(a:Int,b:String){...}
// 正確
let array = [1, 2, 3]
func test(a: Int, b: String) { ... }
  • 括號內側:無空格(()/[]/{}),示例:

    swift
// 錯誤(括號內側有空格)
let dict = [ "key": "value" ]
if ( a > 0 ) { ... }
// 正確
let dict = ["key": "value"]
if (a > 0) { ... }

2. 換行與代碼塊

  • 大括號{:必須和聲明在同一行,閉合}單獨成行,且對齊聲明開頭,示例:
    swift
// 錯誤(Apple明確禁止)
func test() 
{
    print("hello")
}
// 正確(Apple規範)
func test() {
    print("hello")
}
  • 控制流語句(if/for/while/switch):條件後必須加空格,{不換行,示例:
    swift
// 錯誤
if(a>0){...}
for item in array{...}
// 正確
if (a > 0) {
    // 縮進4個空格
    print("positive")
} else if (a < 0) { // else if 和上一個 } 同一行
    print("negative")
} else {
    print("zero")
}
  • switch 語句:case 縮進 4 個空格,:後加空格,示例:
    swift
// 正確(Apple規範)
switch status {
case .pending:
    print("待處理")
case .paid:
    print("已支付")
default:
    print("未知狀態")
}
  • 方法 / 閉包參數:超過 1 個參數時,換行並對齊第一個參數,示例:
    swift
// 正確(Apple推薦)
func fetchUser(
    id: String,
    name: String,
    completion: @escaping (User?) -> Void
) {
    // 邏輯
}

// 閉包換行對齊
let button = UIButton().then {
    $0.setTitle("點擊", for: .normal)
    $0.backgroundColor = .blue
}

3. 命名格式(嚴格對齊 Apple)

  • 類 / 結構體 / 枚舉 / 協議:大駝峯(UpperCamelCase),協議名不加I前綴(Apple 明確反對 C# 風格的I前綴),示例:

    swift
// 正確(Apple規範)
class UserProfileViewController {}
struct ProductModel {}
enum OrderStatus {}
protocol Printable {} // 而非 IPrintable
  • 方法 / 變量 / 常量:小駝峯(lowerCamelCase),常量全大寫 + 下劃線(僅全局常量),示例:
    swift

// 正確
var userName: String = ""
func updateUserAvatar() {}
static let MAX_RETRY_COUNT = 3 // 全局常量
  • 方法參數:外部名(標籤)語義化,內部名簡潔,示例:

    swift
// 正確(Apple推薦:外部名提升可讀性)
func addItem(_ item: String, to list: [String]) -> [String] {
    var newList = list
    newList.append(item)
    return newList
}
// 調用時:addItem("apple", to: fruits)

4. 註釋格式

  • 單行註釋// 後加 1 個空格,註釋內容和代碼隔 1 行(非緊鄰),示例:
    swift
// 正確
let currentTime = Date()

// 獲取用户當前所在時區(註釋説明"為什麼",而非"做什麼")
let timeZone = TimeZone.current
  • 文檔註釋:用///(單行)或/** */(多行),遵循 Apple 的 DocC 規範,示例:
    swift
/// 根據用户ID獲取用户信息
/// - Parameter userId: 用户唯一標識
/// - Returns: 包含用户信息的模型
/// - Throws: 當網絡請求失敗時拋出NetworkError
func getUserInfo(userId: String) throws -> User {
    // 邏輯
}

三、Objective-C 官方格式規範

Apple 對 OC 的格式規範集中在 Coding Guidelines for Cocoa,核心要求:

1. 縮進與空格

  • 縮進:4 個空格(同 Swift);
  • 方法聲明:每個參數換行並對齊,:後加空格,示例:
    objc
// 正確(Apple規範)
- (void)fetchUserWithID:(NSString *)userId
                name:(NSString *)userName
            completion:(void (^)(User *user))completion {
    // 邏輯
}
  • 條件語句:if/for後加空格,{不換行,示例:




    objc









// 正確
if (userID != nil) {
    [self fetchUserWithID:userID name:@"" completion:nil];
}

2. 命名格式

  • 類名:前綴 + 大駝峯(如APPUserViewController,前綴通常為 2-3 個字母);
  • 方法名:小駝峯 + 語義化,動詞開頭,示例:




    objc









// 正確(Apple推薦:動詞+賓語+修飾)
- (void)updateUserAvatar:(UIImage *)avatar;
- (NSArray *)getProductListWithCategory:(NSString *)category;
  • 變量名:小駝峯,成員變量加下劃線前綴(_userName),示例:




    objc









// 正確
@interface UserModel : NSObject
@property (nonatomic, copy) NSString *userName; // 屬性無下劃線
@end

@implementation UserModel
{
    NSString *_nickName; // 成員變量加下劃線
}
@end

3. 括號與換行

  • 消息發送:[]內側無空格,多參數換行對齊,示例:




    objc









// 正確
[self.view addSubview:button];
[self fetchUserWithID:@"123"
                name:@"張三"
            completion:^(User *user) {
                // 閉包縮進4個空格
                NSLog(@"%@", user.userName);
            }];

四、強制對齊 Apple 格式的工具配置

手動遵守容易遺漏,推薦通過 Xcode 內置工具 + SwiftLint 強制對齊 Apple 規範:

1. Xcode 內置格式化(一鍵對齊)

  • 選中代碼 → 右鍵 → Structure > Re-Indent(快捷鍵Ctrl+I),Xcode 會自動按照 Apple 規範調整縮進、空格、換行;
  • 配置自動格式化:Xcode > Settings > Text Editing > Formatting,勾選:
  • Automatically trim trailing whitespace(自動刪除行尾空格);
  • Including whitespace-only lines(刪除空行的空格);
  • Automatically re-indent code(粘貼代碼時自動重新縮進)。

2. SwiftLint 配置(強制遵守 Apple 規範)

SwiftLint 是 Apple 風格的強制檢查工具,配置後編譯時違規則報錯,核心步驟:

  1. 安裝 SwiftLint:brew install swiftlint
  2. 在項目根目錄創建.swiftlint.yml,寫入 Apple 規範的核心規則:




    yaml









# 對齊Apple官方格式規範的核心規則
disabled_rules:
  - line_length # 如需限制行長度可開啓
opt_in_rules:
  - empty_count
  - explicit_init
rules:
  # 縮進:4個空格
  indentation:
    width: 4
    indent_case_contents: true
  # 禁止Tab
  no_tabs:
    severity: error
  # 二元運算符兩側空格
  operator_usage_whitespace:
    severity: error
  # 逗號後空格
  comma:
    severity: error
  # 大括號格式
  brace_style:
    severity: error
    allowed_symbols: [{}]
    mandatory_newline_after_opening_brace: true
  1. 在 Xcode 的Build Phases中添加腳本,編譯時自動檢查:




    bash



    運行






if which swiftlint >/dev/null; then
  swiftlint
else
  echo "SwiftLint not installed, download from https://github.com/realm/SwiftLint"
fi

總結

  1. 核心格式要求:Swift/OC 均遵循 4 個空格縮進、二元運算符 / 逗號後加空格、大括號不換行、命名符合駝峯規則,這是 Apple 格式規範的基礎;
  2. 工具保障:用 Xcode 的Ctrl+I一鍵格式化,配合 SwiftLint 強制檢查,避免手動遺漏;
  3. 關鍵原則:所有格式規範的最終目的是提升可讀性,而非機械遵守 ——Apple 官方也允許在不影響可讀性的前提下靈活調整(如超長方法參數的換行)。