最详尽的 Swift 代码规范指南
1. 代码格式
class SomeClass { func someMethod() { if x == y { /* ... */ } else if x == z { /* ... */ } else { /* ... */ } } /* ... */ }
// 指定类型 let pirateViewController: PirateViewController // 字典语法(注意这里是向左对齐而不是分号对齐) let ninjaDictionary: [String: AnyObject] = [ "fightLikeDairyFarmer": false,"disgusting": true ] // 声明函数 func myFunction<T,U: SomeProtocol where T.RelatedType == U>(firstArgument: U,secondArgument: T) { /* ... */ } // 调用函数 someFunction(someArgument: "Kitten") // 父类 class PirateViewController: UIViewController { /* ... */ } // 协议 extension PirateViewController: UITableViewDataSource { /* ... */ }
let myArray = [1,2,3,4,5]
let myValue = 20 + (30 / 2) * 3 if 1 + 1 == 3 { fatalError("The universe is broken.") } func pancake() -> Pancake { /* ... */ }
// Xcode针对跨多行函数声明缩进 func myFunctionWithManyParameters(parameterOne: String,parameterTwo: String,parameterThree: String) { // Xcode会自动缩进 print("(parameterOne) (parameterTwo) (parameterThree)") } // Xcode针对多行 if 语句的缩进 if myFirstVariable > (mySecondVariable + myThirdVariable) && myFourthVariable == .SomeEnumValue { // Xcode会自动缩进 print("Hello,World!") }
someFunctionWithManyArguments( firstArgument: "Hello,I am a string",secondArgument: resultFromSomeFunction() thirdArgument: someOtherLocalVariable)
someFunctionWithABunchOfArguments( someStringArgument: "hello I am a string",someArrayArgument: [ "dadada daaaa daaaa dadada daaaa daaaa dadada daaaa daaaa","string one is crazy - what is it thinking?" ],someDictionaryArgument: [ "dictionary key 1": "some value 1,but also some more text here","dictionary key 2": "some value 2" ],someClosure: { parameter1 in print(parameter1) })
// 推荐 let firstCondition = x == firstReallyReallyLongPredicateFunction() let secondCondition = y == secondReallyReallyLongPredicateFunction() let thirdCondition = z == thirdReallyReallyLongPredicateFunction() if firstCondition && secondCondition && thirdCondition { // 你要干什么 } // 不推荐 if x == firstReallyReallyLongPredicateFunction() && y == secondReallyReallyLongPredicateFunction() && z == thirdReallyReallyLongPredicateFunction() { // 你要干什么 } 2. 命名
// "HTML" 是变量名的开头,需要全部小写 "html" let htmlBodyContent: String = "<p>Hello,World!</p>" // 推荐使用 ID 而不是 Id let profileID: Int = 1 // 推荐使用 URLFinder 而不是 UrlFinder class URLFinder { /* ... */ }
class MyClassName { // 基元常量使用 k 作为前缀 static let kSomeConstantHeight: CGFloat = 80.0 // 非基元常量也是用 k 作为前缀 static let kDeleteButtonColor = UIColor.redColor() // 对于单例不要使用k作为前缀 static let sharedInstance = MyClassName() /* ... */ }
class SomeClass<T> { /* ... */ } class SomeClass<Model> { /* ... */ } protocol Modelable { associatedtype Model } protocol Sequence { associatedtype IteratorType: Iterator }
// 推荐 class RoundAnimatingButton: UIButton { /* ... */ } // 不推荐 class CustomButton: UIButton { /* ... */ }
// 推荐 class RoundAnimatingButton: UIButton { let animationDuration: NSTimeInterval func startAnimating() { let firstSubview = subviews.first } } // 不推荐 class RoundAnimating: UIButton { let aniDur: NSTimeInterval func srtAnmating() { let v = subviews.first } }
// 推荐 class ConnectionTableViewCell: UITableViewCell { let personImageView: UIImageView let animationDuration: NSTimeInterval // 作为属性名的firstName,很明显是字符串类型,所以不用在命名里不用包含String let firstName: String // 虽然不推荐,这里用 Controller 代替 ViewController 也可以。 let popupController: UIViewController let popupViewController: UIViewController // 如果需要使用UIViewController的子类,如TableViewController,CollectionViewController,SplitViewController,等,需要在命名里标名类型。 let popupTableViewController: UITableViewController // 当使用outlets时,确保命名中标注类型。 @IBOutlet weak var submitButton: UIButton! @IBOutlet weak var emailTextField: UITextField! @IBOutlet weak var nameLabel: UILabel! } // 不推荐 class ConnectionTableViewCell: UITableViewCell { // 这个不是 UIImage,不应该以Image 为结尾命名。 // 建议使用 personImageView let personImage: UIImageView // 这个不是String,应该命名为 textLabel let text: UILabel // animation 不能清晰表达出时间间隔 // 建议使用 animationDuration 或 animationTimeInterval let animation: NSTimeInterval // transition 不能清晰表达出是String // 建议使用 transitionText 或 transitionString let transition: String // 这个是ViewController,不是View let popupView: UIViewController // 由于不建议使用缩写,这里建议使用 ViewController替换 VC let popupVC: UIViewController // 技术上讲这个变量是 UIViewController,但应该表达出这个变量是TableViewController let popupViewController: UITableViewController // 为了保持一致性,建议把类型放到变量的结尾,而不是开始,如submitButton @IBOutlet weak var btnSubmit: UIButton! @IBOutlet weak var buttonSubmit: UIButton! // 在使用outlets 时,变量名内应包含类型名。 // 这里建议使用 firstNameLabel @IBOutlet weak var firstName: UILabel! }
// 这个协议描述的是协议能做的事,应该命名为名词。 protocol TableViewSectionProvider { func rowHeight(atRow row: Int) -> CGFloat var numberOfRows: Int { get } /* ... */ } // 这个协议表达的是行为,以able最为后缀 protocol Loggable { func logCurrentState() /* ... */ } // 因为已经定义类InputTextView,如果依然需要定义相关协议,可以添加Protocol作为后缀。 protocol InputTextViewProtocol { func sendTrackingEvent() func inputText() -> String /* ... */ } 3. 代码风格3.1 综合
// 推荐 let stringOfInts = [1,3].flatMap { String($0) } // ["1","2","3"] // 不推荐 var stringOfInts: [String] = [] for integer in [1,3] { stringOfInts.append(String(integer)) } // 推荐 let evenNumbers = [4,8,15,16,23,42].filter { $0 % 2 == 0 } // [4,42] // 不推荐 var evenNumbers: [Int] = [] for integer in [4,42] { if integer % 2 == 0 { evenNumbers(integer) } }
func pirateName() -> (firstName: String,lastName: String) { return ("Guybrush","Threepwood") } let name = pirateName() let firstName = name.firstName let lastName = name.lastName
myFunctionWithClosure() { [weak self] (error) -> Void in // 方案 1 self?.doSomething() // 或方案 2 guard let strongSelf = self else { return } strongSelf.doSomething() }
// 推荐 if x == y { /* ... */ } // 不推荐 if (x == y) { /* ... */ }
// 推荐 imageView.setImageWithURL(url,type: .person) // 不推荐 imageView.setImageWithURL(url,type: AsyncImageView.Type.person) 3.1.10 在使用类方法的时候不用简写,因为类方法不如 枚举 类型一样,可以根据轻易地推导出上下文。 // 推荐 imageView.backgroundColor = UIColor.whiteColor() // 不推荐 imageView.backgroundColor = .whiteColor()
if someBoolean { // 你想要什么 } else { // 你不想做什么 } do { let fileContents = try readFile("filename.txt") } catch { print(error) } 3.2 访问控制修饰符
// 推荐 private static let kMyPrivateNumber: Int // 不推荐 static private let kMyPrivateNumber: Int
// 推荐 public class Pirate { /* ... */ } // 不推荐 public class Pirate { /* ... */ }
/** 这个变量是private 名字 - warning: 定义为 internal 而不是 private 为了 `@testable`. */ let pirateName = "LeChuck" 3.3 自定义操作符 不推荐使用自定义操作符,如果需要创建函数来替代。 在重写操作符之前,请慎重考虑是否有充分的理由一定要在全局范围内创建新的操作符,而不是使用其他策略。 你可以重载现有的操作符来支持新的类型(特别是 ==),但是新定义的必须保留操作符的原来含义,比如 == 必须用来测试是否相等并返回布尔值。 3.4 Switch 语句 和 枚举
enum Problem { case attitude case hair case hunger(hungerLevel: Int) } func handleProblem(problem: Problem) { switch problem { case .attitude: print("At least I don't have a hair problem.") case .hair: print("Your barber didn't know when to stop.") case .hunger(let hungerLevel): print("The hunger level is (hungerLevel).") } }
func handleDigit(digit: Int) throws { case 0,1,5,6,7,9: print("Yes,(digit) is a digit!") default: throw Error(message: "The given number was not a digit.") } 3.5 可选类型
// 推荐 if someOptional != nil { // 你要做什么 } // 不推荐 if let _ = someOptional { // 你要做什么 }
// 推荐 weak var parentViewController: UIViewController? // 不推荐 weak var parentViewController: UIViewController! unowned var parentViewController: UIViewController
guard let myVariable = myVariable else { return } 3.6 协议 在实现协议的时候,有两种方式来组织你的代码:
请注意 extension 内的代码不能被子类重写,这也意味着测试很难进行。 如果这是经常发生的情况,为了代码一致性最好统一使用第一种办法。否则使用第二种办法,其可以代码分割更清晰。 使用而第二种方法的时候,使用 3.7 属性
var computedProperty: String { if someBool { return "I'm a mighty pirate!" } return "I'm selling these fine leather jackets." }
var computedProperty: String { get { if someBool { return "I'm a mighty pirate!" } return "I'm selling these fine leather jackets." } set { computedProperty = newValue } willSet { print("will set to (newValue)") } didSet { print("did set from (oldValue) to (newValue)") } }
class MyTableViewCell: UITableViewCell { static let kReuseIdentifier = String(MyTableViewCell) static let kCellHeight: CGFloat = 80.0 }
class PirateManager { static let sharedInstance = PirateManager() /* ... */ } 3.8 闭包
// 省略类型 doSomethingWithClosure() { response in print(response) } // 明确指出类型 doSomethingWithClosure() { response: NSURLResponse in print(response) } // map 语句使用简写 [1,3].flatMap { String($0) }
// 因为使用捕捉列表,小括号不能省略。 doSomethingWithClosure() { [weak self] (response: NSURLResponse) in self?.handleResponse(response) } // 因为返回类型,小括号不能省略。 doSomethingWithClosure() { (response: NSURLResponse) -> String in return String(response) }
let completionBlock: (success: Bool) -> Void = { print("Success? (success)") } let completionBlock: () -> Void = { print("Completed!") } let completionBlock: (() -> Void)? = nil 3.9 数组
3.10 错误处理 假设一个函数 例子: func readFile(withFilename filename: String) -> String? { guard let file = openFile(filename) else { return nil } let fileContents = file.read() file.close() return fileContents } func printSomeFile() { let filename = "somefile.txt" guard let fileContents = readFile(filename) else { print("不能打开 (filename).") return } print(fileContents) } 实际上如果预知失败的原因,我们应该使用Swift 中的 定义 错误对象 结构体如下: struct Error: ErrorType { public let file: StaticString public let function: StaticString public let line: UInt public let message: String public init(message: String,file: StaticString = #file,function: StaticString = #function,line: UInt = #line) { self.file = file self.function = function self.line = line self.message = message } } 使用案例: func readFile(withFilename filename: String) throws -> String { guard let file = openFile(filename) else { throw Error(message: “打不开的文件名称 (filename).") } let fileContents = file.read() file.close() return fileContents } func printSomeFile() { do { let fileContents = try readFile(filename) print(fileContents) } catch { print(error) } } 其实项目中还是有一些场景更适合声明为可选类型,而不是错误捕捉和处理,比如在获取远端数据过程中遇到错误,nil作为返回结果是合理的,也就是声明返回可选类型比错误处理更合理。 整体上说,如果一个方法有可能失败,并且使用可选类型作为返回类型会导致错误原因湮没,不妨考虑抛出错误而不是吃掉它。 3.11 使用
// 推荐 func eatDoughnut(atIndex index: Int) { guard index >= 0 && index < doughnuts else { // 如果 index 超出允许范围,提前返回。 return } let doughnut = doughnuts[index] eat(doughnut) } // 不推荐 func eatDoughnuts(atIndex index: Int) { if index >= 0 && index < donuts.count { let doughnut = doughnuts[index] eat(doughnut) } }
// 推荐 guard let monkeyIsland = monkeyIsland else { return } bookVacation(onIsland: monkeyIsland) bragAboutVacation(onIsland: monkeyIsland) // 不推荐 if let monkeyIsland = monkeyIsland { bookVacation(onIsland: monkeyIsland) bragAboutVacation(onIsland: monkeyIsland) } // 禁止 if monkeyIsland == nil { return } bookVacation(onIsland: monkeyIsland!) bragAboutVacation(onIsland: monkeyIsland!)
// if 语句更有可读性 if operationFailed { return } // guard 语句这里有更好的可读性 guard isSuccessful else { return } // 双重否定不易被理解 - 不要这么做 guard !operationFailed else { return }
// 推荐 if isFriendly { print("你好,远路来的朋友!") } else { print(“穷小子,哪儿来的?") } // 不推荐 guard isFriendly else { print("穷小子,哪儿来的?") return } print("你好,远路来的朋友!")
if let monkeyIsland = monkeyIsland { bookVacation(onIsland: monkeyIsland) } if let woodchuck = woodchuck where canChuckWood(woodchuck) { woodchuck.chuckWood() }
// 组合在一起因为可能立即返回 guard let thingOne = thingOne,let thingTwo = thingTwo,let thingThree = thingThree else { return } // 使用独立的语句 因为每个场景返回不同的错误 guard let thingOne = thingOne else { throw Error(message: "Unwrapping thingOne failed.") } guard let thingTwo = thingTwo else { throw Error(message: "Unwrapping thingTwo failed.") } guard let thingThree = thingThree else { throw Error(message: "Unwrapping thingThree failed.") } 4. 文档/注释4.1 文档如果一个函数比O(1) 复杂度高,你需要考虑为函数添加注释,因为函数签名(方法名和参数列表) 并不是那么的一目了然,这里推荐比较流行的插件VVDocumenter. 不论出于何种原因,如果有任何奇淫巧计不易理解的代码,都需要添加注释,对于复杂的 类/结构体/枚举/协议/属性 都需要添加注释。所有公开的 函数/类/变量/枚举/协议/属性/常数 也都需要添加文档,特别是函数声明(包括名称和参数列表) 不是那么清晰的时候。 写文档时,确保参照苹果文档中提及的标记语法合集。 在注释文档完成后,你应检查格式是否正确。 规则:
/** ## 功能列表 这个类提供下一下很赞的功能,如下: - 功能 1 - 功能 2 - 功能 3 ## 例子 这是一个代码块使用四个空格作为缩进的例子。 let myAwesomeThing = MyAwesomeClass() myAwesomeThing.makeMoney() ## 警告 使用的时候总注意以下几点 1. 第一点 2. 第二点 3. 第三点 */ class MyAwesomeClass { /* ... */ }
4.2 其他注释原则
class Pirate { // MARK: - 实例属性 private let pirateName: String // MARK: - 初始化 init() { /* ... */ } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |