《Swift3.0从入门到出家》——原创连载iOS 开发 iOS Developer

Swift/Cocoa 编码规范(中文)

2016-06-02  本文已影响103人  LovelyYilia

注:以下皆为翻译,如有错误或疏漏,请指正。谢谢☺

简介

SlideShare 版

Swift

官方 SlideShare Swift 代码规范

这份规范是用于 swift 编写 iOS8 及以上应用。

目录


<a id="xcode-preferences"/>

Xcode Preferences

Switch

var value = 2
var test: String?

switch value {
case 1:
    test = "abc"
default:
    test = "xyz"
}
struct TestValue {
    enum Val {
        case A
        case B
    }
    var value: Val = .A
    var detail: String = "Test"
}
var testValue = TestValue()

switch (testValue.value, testValue.detail) {
case (.A, "Test"):
    println("This is printed")
default:
    println("This is not printed")
}
var test = "Hello"

switch test {
case "Hello"
    print("It prints")
case "World"
    print("It doesn't")
default:
    assert(false, "Useful message for developer")
}

<a id=""/>

Properties

var computedProp: String {
    if someBool {
        return "Hello"
      }
}
var computedProp: String {
    get {
        if someBool {
            return "Hello"
          }
    }
    set {
        println(newValue)
    }
}
var property = 10 {
    willSet {
        println("willSet")
    }
    didSet {
        println("didSet")
    }
}
var property = 10 {
    willSet {
        if newValue == 10 {
            println("It’s 10")
         }
    }
    didSet {
         if oldValue == 10 {
               println("It was 10")
         }
    }
}
class Test {
    static let ConstantValue: String = "TestString"
}

<a id=""/>

Closures

doSomethingWithCompletion() { param1 in
    println("\(param1)")
}
// Definition
func newMethod(input: Int, onComplete methodToRun: (input: Int) -> Void) {
    // content
}

// Usage
newMethod(10) { param in
    println("output: \(param)"")
}
testMethod(param: 2.5,
      success: {
        println("success")
      },
      failure: {
        println("failure")
      })
array1.map { /* content */ }
func takeClosure(aClosure: () -> Void) {
    // content
}
func noReturn() {
    // content
}
func foo(something: () -> Void) {
    something()
}

func doEverything() {
    let doSomething = {
        var x = 1
        for 1...3 {
            x++
        }
        println(x)
    }
    foo(doSomething)
}

<a id=""/>

Identifiers

class Test {

    var a: (() -> Void)?
    var b: Int = 3

    func foo(a: () -> Void) {
        self.a = a
    }

    func foo1() {
        foo() {
            println(self.b)
        }
    }
}
static var testVar: String
var someDictionary: [String : Int]
class TestClass {
    let ConstantValue = 3
}
struct Constants {
    static let A = "A"
    static let B = "B"
}

<a id=""/>

Singleton

class ClassA {

    static let sharedInstance: ClassA = ClassA()
    
    private init() {
        // ...
    }
}

Note: Xcode currently (6.0.1) does not indent properly in this case. Use the indentation specified above.

<a id="optionals"/>

Optionals

func possibleBike() -> Bike? {
    // content
}

let bike = possibleBike()
if let bike = bike {
    // content
}

<a id="strings"/>

Strings

var newString = "Hello"
newString += " world!"

Note: do not concatenate user-facing strings as the ordering could change in different languages

<a id="enums"/>

Enums

enum TestEnum {
    case A
    case B
}

var theValue: TestEnum?
var shouldBeA = true

if shouldBeA {
    theValue = .A
} else {
    theValue = .B
}
var testValue: TestEnum = .A

<a id="documentation"/>

Documentation

/// This method does nothing
func foo() {
    // content
}
/**
 This method does something.
 It's very useful.
 */
func foo2() {
    // content
}

Note: Make sure to test your documentation by checking it's Quick Documentation by option-clicking on the method name.

/**
 This method has parameters and a return type.

 - Parameter input: This is an input parameter.
 - Returns: True if it worked; false otherwise.
 */
func foo3(input: String) -> Bool {
    // content
}

Note: The following section refers to marks, which are Swift's version of #pragma mark in Objective-C to separate code. There are 2 types of marks: section marks and sub-section marks.

Section Marks:

   // MARK: - Section Name

Sub-section Marks:

   // MARK: Sub-section Name
class Stuff {

    // MARK: - Instance methods

    func newMethod() {
        // content
    }
}
// NewProtocol.swift //
protocol NewProtocol {
    func reqMethod()
}

// Test.swift //
class Test {

    // content
}

// MARK: - Protocols
// MARK: NewProtocol

extension Test: NewProtocol {
    func reqMethod() {
        // content
    }
}

Cocoa

目录


<a id="protocols"></a>

Protocols

protocol ReusableView {
    static var ReuseIdentifier: String { get }
    static var NibName: String { get }
}

<a id="uitableview"></a>

UITableView & UICollectionView

class TableViewCell: UITableViewCell, ReusableView {
    static let ReuseIdentifier: String = "TableViewCellIdentifier"
    static let NibName: String = "CustomTableViewCell"
}

原因: 注册一个UITableView 或 UICollectionView的重用 cell , 你需要 nib 名称和重用 identifier.

<a id="strings"></a>

Strings

// Localizable.strings //
// <App Section>
"user_facing_string_key" = "This is a user-facing string."

// Someting.swift //
var userFacing = NSLocalizedString("user_facing_string_key", comment: "")

<a id="nsnotification"></a>

NSNotification

com.linkedin.slideshare.notification_name
struct GlobalNotifications {
    static let ABC = ""
}
private lazy var handleNotification: (NSNotification!) -> Void { [weak self] notification in
    // Handle the notification
}

原因: This way you can define capture semantics for self and also use the identifier as the selector in the addObserver method (see below) instead of a string.确保编译安全.

func registerNotifications() {
    let notificationCenter = NSNotificationCenter.defaultCenter()

    notificationCenter.addObserver(self, selector: handleNotificationABC, name: GlobalNotifications.ABC, object: nil)
}

func deregisterNotifications() {
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

<a id="app-delegate"></a>

App Delegate

class AppInitializer {
    func onAppStart() {
        // content
    }
}

<a id="core-foundation"></a>

Core Foundation

var rect = CGRect(x: 10, y: 10, width: 45, height: 300)
var zeroRect = CGRect.zeroRect

<a id="view-controllers"></a>

View Controllers

static func createInstance() -> MasterViewController {
    return UIStoryboard.initialControllerFromStoryboard("Master") as! MasterViewController
}

Reasoning: 如果你不会创建当前类的子类,则用static ,否则用 class func

static func createInstanceWithId(id: Int) -> MasterViewController {
        let masterViewController = createInstance()
        masterViewController.id = id
        return masterViewController
}

<a id="uiview"></a>

UIView

class CustomView: UIView {

    private static let NibName: String = "CustomView"

    static func createInstance() -> CustomView {
        return NSBundle.mainBundle().loadNibNamed(nibName, owner: nil, options: nil)[0] as! CustomView
    }
}

<a id="objective-c-interoperability"></a>

Objective-C Interoperability

// <Product-Name>-Bridging-Header.h
#import "SDWebImageHeader.h"

// SDWebImageHeader.h
#import <SDWebImage/UIImageView+WebCache.h>
#import <SDWebImage/UIImage+MultiFormat.h>
#import <SDWebImage/SDWebImagePrefetcher.h>
上一篇 下一篇

猜你喜欢

热点阅读