1
0
mirror of https://github.com/adambard/learnxinyminutes-docs.git synced 2025-08-06 06:47:54 +02:00

Merge pull request #2899 from damian-rzeszot/swift-style-guidelines

[swift/many] Style guidelines
This commit is contained in:
Andre Polykanine A.K.A. Menelion Elensúlë
2017-10-09 23:03:33 +03:00
committed by GitHub
8 changed files with 121 additions and 121 deletions

View File

@@ -440,13 +440,13 @@ if let circle = myEmptyCircle {
// Wie Klassen auch können sie Methoden haben // Wie Klassen auch können sie Methoden haben
enum Suit { enum Suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }
@@ -455,35 +455,35 @@ enum Suit {
// Enum-Werte können vereinfacht geschrieben werden, es muss nicht der Enum-Typ // Enum-Werte können vereinfacht geschrieben werden, es muss nicht der Enum-Typ
// genannt werden, wenn die Variable explizit deklariert wurde // genannt werden, wenn die Variable explizit deklariert wurde
var suitValue: Suit = .Hearts var suitValue: Suit = .hearts
// Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte" // Nicht-Integer-Enums brauchen direkt zugewiesene "Rohwerte"
enum BookName: String { enum BookName: String {
case John = "John" case john = "John"
case Luke = "Luke" case luke = "Luke"
} }
print("Name: \(BookName.John.rawValue)") print("Name: \(BookName.john.rawValue)")
// Enum mit assoziierten Werten // Enum mit assoziierten Werten
enum Furniture { enum Furniture {
// mit Int assoziiert // mit Int assoziiert
case Desk(height: Int) case desk(height: Int)
// mit String und Int assoziiert // mit String und Int assoziiert
case Chair(String, Int) case chair(String, Int)
func description() -> String { func description() -> String {
switch self { switch self {
case .Desk(let height): case .desk(let height):
return "Desk with \(height) cm" return "Desk with \(height) cm"
case .Chair(let brand, let height): case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm" return "Chair of \(brand) with \(height) cm"
} }
} }
} }
var desk: Furniture = .Desk(height: 80) var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm" print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair("Foo", 40) var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm" print(chair.description()) // "Chair of Foo with 40 cm"

View File

@@ -446,48 +446,48 @@ if let circle = myEmptyCircle {
// Al igual que las clases, pueden contener métodos // Al igual que las clases, pueden contener métodos
enum Suit { enum Suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }
// Los valores de enum permite la sintaxis corta, sin necesidad de poner // Los valores de enum permite la sintaxis corta, sin necesidad de poner
// el tipo del enum cuando la variable es declarada de manera explícita // el tipo del enum cuando la variable es declarada de manera explícita
var suitValue: Suit = .Hearts var suitValue: Suit = .hearts
// Enums de tipo no-entero requiere asignaciones de valores crudas directas // Enums de tipo no-entero requiere asignaciones de valores crudas directas
enum BookName: String { enum BookName: String {
case John = "John" case john = "John"
case Luke = "Luke" case luke = "Luke"
} }
print("Name: \(BookName.John.rawValue)") print("Name: \(BookName.john.rawValue)")
// Enum con valores asociados // Enum con valores asociados
enum Furniture { enum Furniture {
// Asociación con Int // Asociación con Int
case Desk(height: Int) case desk(height: Int)
// Asociación con String e Int // Asociación con String e Int
case Chair(String, Int) case chair(String, Int)
func description() -> String { func description() -> String {
switch self { switch self {
case .Desk(let height): case .desk(let height):
return "Desk with \(height) cm" return "Desk with \(height) cm"
case .Chair(let brand, let height): case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm" return "Chair of \(brand) with \(height) cm"
} }
} }
} }
var desk: Furniture = .Desk(height: 80) var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm" print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair("Foo", 40) var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm" print(chair.description()) // "Chair of Foo with 40 cm"

View File

@@ -389,13 +389,13 @@ if mySquare === mySquare {
// Podem conter métodos do mesmo jeito que classes. // Podem conter métodos do mesmo jeito que classes.
enum Suit { enum Suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }

View File

@@ -445,49 +445,49 @@ if let circle = myEmptyCircle {
// Enums pode opcionalmente ser um tipo especifico ou não. // Enums pode opcionalmente ser um tipo especifico ou não.
// Enums podem conter métodos tal como as classes. // Enums podem conter métodos tal como as classes.
enum Suit { enum suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }
// Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum // Os valores de Enum permitem syntax reduzida, não é preciso escrever o tipo do enum
// quando a variável é explicitamente definida. // quando a variável é explicitamente definida.
var suitValue: Suit = .Hearts var suitValue: Suit = .hearts
// Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas // Enums que não sejam inteiros obrigam a atribuições valor bruto (raw value) diretas
enum BookName: String { enum BookName: String {
case John = "John" case john = "John"
case Luke = "Luke" case luke = "Luke"
} }
print("Name: \(BookName.John.rawValue)") print("Name: \(BookName.john.rawValue)")
// Enum com valores associados // Enum com valores associados
enum Furniture { enum Furniture {
// Associar com um inteiro (Int) // Associar com um inteiro (Int)
case Desk(height: Int) case desk(height: Int)
// Associar com uma String e um Int // Associar com uma String e um Int
case Chair(String, Int) case chair(String, Int)
func description() -> String { func description() -> String {
switch self { switch self {
case .Desk(let height): case .desk(let height):
return "Desk with \(height) cm" return "Desk with \(height) cm"
case .Chair(let brand, let height): case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm" return "Chair of \(brand) with \(height) cm"
} }
} }
} }
var desk: Furniture = .Desk(height: 80) var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm" print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair("Foo", 40) var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm" print(chair.description()) // "Chair of Foo with 40 cm"

View File

@@ -376,14 +376,14 @@ print("Имя :\(name)") // Имя: Яков
// Протокол `Error` используется для перехвата выбрасываемых ошибок // Протокол `Error` используется для перехвата выбрасываемых ошибок
enum MyError: Error { enum MyError: Error {
case BadValue(msg: String) case badValue(msg: String)
case ReallyBadValue(msg: String) case reallyBadValue(msg: String)
} }
// фунции помеченные словом `throws` должны вызываться с помощью `try` // фунции помеченные словом `throws` должны вызываться с помощью `try`
func fakeFetch(value: Int) throws -> String { func fakeFetch(value: Int) throws -> String {
guard 7 == value else { guard 7 == value else {
throw MyError.ReallyBadValue(msg: "Действительно плохое значение") throw MyError.reallyBadValue(msg: "Действительно плохое значение")
} }
return "тест" return "тест"
@@ -401,7 +401,7 @@ func testTryStuff() {
do { do {
// обычно try оператор, позволяющий обработать ошибку в `catch` блоке // обычно try оператор, позволяющий обработать ошибку в `catch` блоке
try fakeFetch(value: 1) try fakeFetch(value: 1)
} catch MyError.BadValue(let msg) { } catch MyError.badValue(let msg) {
print("Ошибка: \(msg)") print("Ошибка: \(msg)")
} catch { } catch {
// все остальное // все остальное
@@ -535,49 +535,49 @@ if let circle = myEmptyCircle {
// Они могут содержать методы подобно классам. // Они могут содержать методы подобно классам.
enum Suit { enum Suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }
// Значения перечислений допускают сокращенный синтаксис, нет необходимости // Значения перечислений допускают сокращенный синтаксис, нет необходимости
// указывать тип перечисления, когда переменная объявляется явно // указывать тип перечисления, когда переменная объявляется явно
var suitValue: Suit = .Hearts var suitValue: Suit = .hearts
// Значения нецелочисленных перечислений должны быть указаны явно // Значения нецелочисленных перечислений должны быть указаны явно
// или могут выводится с помощью функции `rawValue` из имени // или могут выводится с помощью функции `rawValue` из имени
enum BookName: String { enum BookName: String {
case John case john
case Luke = "Лука" case luke = "Лука"
} }
print("Имя: \(BookName.John.rawValue)") print("Имя: \(BookName.john.rawValue)")
// Перечисление (enum) со связанными значениями // Перечисление (enum) со связанными значениями
enum Furniture { enum Furniture {
// Связать с типом Int // Связать с типом Int
case Desk(height: Int) case desk(height: Int)
// Связать с типами String и Int // Связать с типами String и Int
case Chair(String, Int) case chair(String, Int)
func description() -> String { func description() -> String {
switch self { switch self {
case .Desk(let height): case .desk(let height):
return "Письменный стол высотой \(height) см." return "Письменный стол высотой \(height) см."
case .Chair(let brand, let height): case .chair(let brand, let height):
return "Стул марки \(brand) высотой \(height) см." return "Стул марки \(brand) высотой \(height) см."
} }
} }
} }
var desk: Furniture = .Desk(height: 80) var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Письменный стол высотой 80 см." print(desk.description()) // "Письменный стол высотой 80 см."
var chair = Furniture.Chair("Foo", 40) var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Стул марки Foo высотой 40 см." print(chair.description()) // "Стул марки Foo высотой 40 см."

View File

@@ -361,14 +361,14 @@ print("Name is \(name)") // Name is Them
// The `Error` protocol is used when throwing errors to catch // The `Error` protocol is used when throwing errors to catch
enum MyError: Error { enum MyError: Error {
case BadValue(msg: String) case badValue(msg: String)
case ReallyBadValue(msg: String) case reallyBadValue(msg: String)
} }
// functions marked with `throws` must be called using `try` // functions marked with `throws` must be called using `try`
func fakeFetch(value: Int) throws -> String { func fakeFetch(value: Int) throws -> String {
guard 7 == value else { guard 7 == value else {
throw MyError.ReallyBadValue(msg: "Some really bad value") throw MyError.reallyBadValue(msg: "Some really bad value")
} }
return "test" return "test"
@@ -385,7 +385,7 @@ func testTryStuff() {
do { do {
// normal try operation that provides error handling via `catch` block // normal try operation that provides error handling via `catch` block
try fakeFetch(value: 1) try fakeFetch(value: 1)
} catch MyError.BadValue(let msg) { } catch MyError.badValue(let msg) {
print("Error message: \(msg)") print("Error message: \(msg)")
} catch { } catch {
// must be exhaustive // must be exhaustive
@@ -518,49 +518,49 @@ if let circle = myEmptyCircle {
// They can contain methods like classes. // They can contain methods like classes.
enum Suit { enum Suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }
// Enum values allow short hand syntax, no need to type the enum type // Enum values allow short hand syntax, no need to type the enum type
// when the variable is explicitly declared // when the variable is explicitly declared
var suitValue: Suit = .Hearts var suitValue: Suit = .hearts
// String enums can have direct raw value assignments // String enums can have direct raw value assignments
// or their raw values will be derived from the Enum field // or their raw values will be derived from the Enum field
enum BookName: String { enum BookName: String {
case John case john
case Luke = "Luke" case luke = "Luke"
} }
print("Name: \(BookName.John.rawValue)") print("Name: \(BookName.john.rawValue)")
// Enum with associated Values // Enum with associated Values
enum Furniture { enum Furniture {
// Associate with Int // Associate with Int
case Desk(height: Int) case desk(height: Int)
// Associate with String and Int // Associate with String and Int
case Chair(String, Int) case chair(String, Int)
func description() -> String { func description() -> String {
switch self { switch self {
case .Desk(let height): case .desk(let height):
return "Desk with \(height) cm" return "Desk with \(height) cm"
case .Chair(let brand, let height): case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm" return "Chair of \(brand) with \(height) cm"
} }
} }
} }
var desk: Furniture = .Desk(height: 80) var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm" print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair("Foo", 40) var chair = Furniture.chair("Foo", 40)
print(chair.description()) // "Chair of Foo with 40 cm" print(chair.description()) // "Chair of Foo with 40 cm"

View File

@@ -443,47 +443,47 @@ if let daire = benimBosDairem {
// Sınıflar gibi metotlar içerebilirler. // Sınıflar gibi metotlar içerebilirler.
enum Kart { enum Kart {
case Kupa, Maca, Sinek, Karo case kupa, maca, sinek, karo
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Maca: return "♤" case .maca: return "♤"
case .Kupa: return "♡" case .kupa: return "♡"
case .Karo: return "♢" case .karo: return "♢"
case .Sinek: return "♧" case .sinek: return "♧"
} }
} }
} }
// Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz. // Enum değerleri kısayol syntaxa izin verir. Eğer değişken tipi açık olarak belirtildiyse enum tipini yazmaya gerek kalmaz.
var kartTipi: Kart = .Kupa var kartTipi: Kart = .kupa
// Integer olmayan enumlar direk değer (rawValue) atama gerektirir. // Integer olmayan enumlar direk değer (rawValue) atama gerektirir.
enum KitapAdi: String { enum KitapAdi: String {
case John = "John" case john = "John"
case Luke = "Luke" case luke = "Luke"
} }
print("Name: \(KitapAdi.John.rawValue)") print("Name: \(KitapAdi.john.rawValue)")
// Değerlerle ilişkilendirilmiş Enum // Değerlerle ilişkilendirilmiş Enum
enum Mobilya { enum Mobilya {
// Int ile ilişkilendirilmiş // Int ile ilişkilendirilmiş
case Masa(yukseklik: Int) case masa(yukseklik: Int)
// String ve Int ile ilişkilendirilmiş // String ve Int ile ilişkilendirilmiş
case Sandalye(String, Int) case sandalye(String, Int)
func aciklama() -> String { func aciklama() -> String {
switch self { switch self {
case .Masa(let yukseklik): case .masa(let yukseklik):
return "Masa boyu \(yukseklik) cm" return "Masa boyu \(yukseklik) cm"
case .Sandalye(let marka, let yukseklik): case .sandalye(let marka, let yukseklik):
return "\(brand) marka sandalyenin boyu \(yukseklik) cm" return "\(brand) marka sandalyenin boyu \(yukseklik) cm"
} }
} }
} }
var masa: Mobilya = .Masa(yukseklik: 80) var masa: Mobilya = .masa(yukseklik: 80)
print(masa.aciklama()) // "Masa boyu 80 cm" print(masa.aciklama()) // "Masa boyu 80 cm"
var sandalye = Mobilya.Sandalye("Foo", 40) var sandalye = Mobilya.sandalye("Foo", 40)
print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm" print(sandalye.aciklama()) // "Foo marka sandalyenin boyu 40 cm"

View File

@@ -445,47 +445,47 @@ if let circle = myEmptyCircle {
// 枚举可以像类一样,拥有方法 // 枚举可以像类一样,拥有方法
enum Suit { enum Suit {
case Spades, Hearts, Diamonds, Clubs case spades, hearts, diamonds, clubs
func getIcon() -> String { func getIcon() -> String {
switch self { switch self {
case .Spades: return "♤" case .spades: return "♤"
case .Hearts: return "♡" case .hearts: return "♡"
case .Diamonds: return "♢" case .diamonds: return "♢"
case .Clubs: return "♧" case .clubs: return "♧"
} }
} }
} }
// 当变量类型明确指定为某个枚举类型时,赋值时可以省略枚举类型 // 当变量类型明确指定为某个枚举类型时,赋值时可以省略枚举类型
var suitValue: Suit = .Hearts var suitValue: Suit = .hearts
// 非整型的枚举类型需要在定义时赋值 // 非整型的枚举类型需要在定义时赋值
enum BookName: String { enum BookName: String {
case John = "John" case john = "John"
case Luke = "Luke" case luke = "Luke"
} }
print("Name: \(BookName.John.rawValue)") print("Name: \(BookName.john.rawValue)")
// 与特定数据类型关联的枚举 // 与特定数据类型关联的枚举
enum Furniture { enum Furniture {
// 和 Int 型数据关联的枚举记录 // 和 Int 型数据关联的枚举记录
case Desk(height: Int) case desk(height: Int)
// 和 String, Int 关联的枚举记录 // 和 String, Int 关联的枚举记录
case Chair(brand: String, height: Int) case chair(brand: String, height: Int)
func description() -> String { func description() -> String {
switch self { switch self {
case .Desk(let height): case .desk(let height):
return "Desk with \(height) cm" return "Desk with \(height) cm"
case .Chair(let brand, let height): case .chair(let brand, let height):
return "Chair of \(brand) with \(height) cm" return "Chair of \(brand) with \(height) cm"
} }
} }
} }
var desk: Furniture = .Desk(height: 80) var desk: Furniture = .desk(height: 80)
print(desk.description()) // "Desk with 80 cm" print(desk.description()) // "Desk with 80 cm"
var chair = Furniture.Chair(brand: "Foo", height: 40) var chair = Furniture.chair(brand: "Foo", height: 40)
print(chair.description()) // "Chair of Foo with 40 cm" print(chair.description()) // "Chair of Foo with 40 cm"