diff options
| -rw-r--r-- | c.html.markdown | 2 | ||||
| -rw-r--r-- | matlab.html.markdown | 2 | ||||
| -rw-r--r-- | ru-ru/go-ru.html.markdown | 42 | ||||
| -rw-r--r-- | swift.html.markdown | 334 | 
4 files changed, 281 insertions, 99 deletions
| diff --git a/c.html.markdown b/c.html.markdown index 8e170300..79b7aec7 100644 --- a/c.html.markdown +++ b/c.html.markdown @@ -573,7 +573,7 @@ typedef void (*my_fnp_type)(char *);  '\''; // single quote  '\"'; // double quote  '\xhh'; // hexadecimal number. Example: '\xb' = vertical tab character -'\ooo'; // octal number. Example: '\013' = vertical tab character +'\0oo'; // octal number. Example: '\013' = vertical tab character  //print formatting:  "%d";    // integer diff --git a/matlab.html.markdown b/matlab.html.markdown index d9a82890..9dae8ef2 100644 --- a/matlab.html.markdown +++ b/matlab.html.markdown @@ -85,7 +85,7 @@ load myFile.mat y % no parentheses, and spaces instead of commas  % Logicals can be applied to matrices:  A > 5  % for each element, if condition is true, that element is 1 in returned matrix -A[ A > 5 ]  +A( A > 5 )  % returns a vector containing the elements in A for which condition is true  % Strings diff --git a/ru-ru/go-ru.html.markdown b/ru-ru/go-ru.html.markdown index 5b9d8ebf..44a22b45 100644 --- a/ru-ru/go-ru.html.markdown +++ b/ru-ru/go-ru.html.markdown @@ -13,11 +13,11 @@ lang: ru-ru  ---  Go - это язык общего назначения, целью которого является удобство, простота, -конкуррентность. Это не тренд в компьютерных науках, а новейший и быстрый +конкурентность. Это не тренд в компьютерных науках, а новейший и быстрый  способ решать насущные проблемы.  Концепции Go схожи с другими императивными статически типизированными языками. -Быстро компилируется и быстро исполняется, имеет легкие в понимании конструкции +Быстро компилируется и быстро исполняется, имеет лёгкие в понимании конструкции  для создания масштабируемых и многопоточных программ.  Может похвастаться отличной стандартной библиотекой и большим комьюнити, полным @@ -57,7 +57,7 @@ func main() {  func beyondHello() {      var x int // Переменные должны быть объявлены до их использования.      x = 3     // Присвоение значения переменной. -    // Краткое определение := позволяет объявить перменную с автоматической +    // Краткое определение := позволяет объявить переменную с автоматической      // подстановкой типа из значения.      y := 4      sum, prod := learnMultiple(x, y)        // Функция возвращает два значения. @@ -70,7 +70,7 @@ func learnMultiple(x, y int) (sum, prod int) {      return x + y, x * y // Возврат двух значений.  } -// Некотрые встроенные типы и литералы. +// Некоторые встроенные типы и литералы.  func learnTypes() {      // Краткое определение переменной говорит само за себя.      s := "Learn Go!" // Тип string. @@ -97,7 +97,7 @@ func learnTypes() {      // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои      // преимущества, но слайсы используются гораздо чаще. -    s3 := []int{4, 5, 9}    // Сравните с a3. Тут нет троеточия. +    s3 := []int{4, 5, 9}    // Сравните с a3, тут нет троеточия.      s4 := make([]int, 4)    // Выделение памяти для слайса из 4-х int (нули).      var d2 [][]float64      // Только объявление, память не выделяется.      bs := []byte("a slice") // Синтаксис приведения типов. @@ -113,7 +113,7 @@ func learnTypes() {      delete(m, "three") // Встроенная функция, удаляет элемент из map-а.      // Неиспользуемые переменные в Go являются ошибкой. -    // Нижнее подчеркивание позволяет игнорировать такие переменные. +    // Нижнее подчёркивание позволяет игнорировать такие переменные.      _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs      // Вывод считается использованием переменной.      fmt.Println(s, c, a4, s3, d2, m) @@ -121,16 +121,16 @@ func learnTypes() {      learnFlowControl() // Идем дальше.  } -// У Go есть полноценный сборщик мусора. В нем есть указатели но нет арифметики +// У Go есть полноценный сборщик мусора. В нем есть указатели, но нет арифметики  // указателей. Вы можете допустить ошибку с указателем на nil, но не с  // инкрементацией указателя.  func learnMemory() (p, q *int) {      // Именованные возвращаемые значения p и q являются указателями на int.      p = new(int) // Встроенная функция new выделяет память. -    // Выделенный int проинициализирован нулем, p больше не содержит nil. +    // Выделенный int проинициализирован нулём, p больше не содержит nil.      s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов.      s[3] = 7             // Присвоить значение одному из них. -    r := -2              // Определить еще одну локальную переменную. +    r := -2              // Определить ещё одну локальную переменную.      return &s[3], &r     // Амперсанд(&) обозначает получение адреса переменной.  } @@ -139,7 +139,7 @@ func expensiveComputation() float64 {  }  func learnFlowControl() { -    // If-ы всегда требуют наличине фигурных скобок, но не круглых. +    // If-ы всегда требуют наличие фигурных скобок, но не круглых.      if true {          fmt.Println("told ya")      } @@ -178,7 +178,7 @@ func learnFlowControl() {      }      // Функции являются замыканиями.      xBig := func() bool { -        return x > 10000 // Ссылается на x, объявленый выше switch. +        return x > 10000 // Ссылается на x, объявленный выше switch.      }      fmt.Println("xBig:", xBig()) // true (т.к. мы присвоили x = e^10).      x = 1.3e3                    // Тут х == 1300 @@ -189,7 +189,7 @@ func learnFlowControl() {  love:      learnDefer()      // Быстрый обзор важного ключевого слова. -    learnInterfaces() // О! Интерфейсы, идем далее. +    learnInterfaces() // О! Интерфейсы, идём далее.  }  func learnDefer() (ok bool) { @@ -214,7 +214,7 @@ type pair struct {  // Объявление метода для типа pair. Теперь pair реализует интерфейс Stringer.  func (p pair) String() string { // p в данном случае называют receiver-ом. -    // Sprintf – еще одна функция из пакета fmt. +    // Sprintf – ещё одна функция из пакета fmt.      // Обращение к полям p через точку.      return fmt.Sprintf("(%d, %d)", p.x, p.y)  } @@ -234,7 +234,7 @@ func learnInterfaces() {      fmt.Println(p) // Вывод такой же, что и выше. Println вызывает метод String.      fmt.Println(i) // Вывод такой же, что и выше. -    learnVariadicParams("Учиться", "учиться", "и еще раз учиться!") +    learnVariadicParams("Учиться", "учиться", "и ещё раз учиться!")  }  // Функции могут иметь варьируемое количество параметров. @@ -263,22 +263,22 @@ func learnErrorHandling() {          // выведет "strconv.ParseInt: parsing "non-int": invalid syntax"          fmt.Println(err)      } -    // Мы еще обратимся к интерфейсам чуть позже, а пока... +    // Мы ещё обратимся к интерфейсам чуть позже, а пока...      learnConcurrency()  } -// c – это тип данных channel (канал), объект для конкуррентного взаимодействия. +// c – это тип данных channel (канал), объект для конкурентного взаимодействия.  func inc(i int, c chan int) {      c <- i + 1 // когда channel слева, <- являтся оператором "отправки".  } -// Будем использовать функцию inc для конкуррентной инкрементации чисел. +// Будем использовать функцию inc для конкурентной инкрементации чисел.  func learnConcurrency() {      // Тот же make, что и в случае со slice. Он предназначен для выделения      // памяти и инициализации типов slice, map и channel.      c := make(chan int) -    // Старт трех конкуррентных goroutine. Числа будут инкрементированы -    // конкуррентно и, может быть параллельно, если машина правильно +    // Старт трех конкурентных goroutine. Числа будут инкрементированы +    // конкурентно и, может быть параллельно, если машина правильно      // сконфигурирована и позволяет это делать. Все они будут отправлены в один      // и тот же канал.      go inc(0, c) // go начинает новую горутину. @@ -291,7 +291,7 @@ func learnConcurrency() {      cs := make(chan string)       // другой канал, содержит строки.      cc := make(chan chan string)  // канал каналов со строками.      go func() { c <- 84 }()       // пуск новой горутины для отправки значения -    go func() { cs <- "wordy" }() // еще раз, теперь для cs +    go func() { cs <- "wordy" }() // ещё раз, теперь для cs      // Select тоже что и switch, но работает с каналами. Он случайно выбирает      // готовый для взаимодействия канал.      select { @@ -327,7 +327,7 @@ func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) {  Основа всех основ в Go это [официальный веб сайт](http://golang.org/).  Там можно пройти туториал, поиграться с интерактивной средой Go и почитать -объемную документацию. +объёмную документацию.  Для живого ознакомления рекомендуется почитать исходные коды [стандартной  библиотеки Go](http://golang.org/src/pkg/). Отлично задокументированная, она diff --git a/swift.html.markdown b/swift.html.markdown index 6d98b067..e7f2f9a2 100644 --- a/swift.html.markdown +++ b/swift.html.markdown @@ -2,30 +2,51 @@  language: swift  contributors:    - ["Grant Timmerman", "http://github.com/grant"] +  - ["Christopher Bess", "http://github.com/cbess"]  filename: learnswift.swift  ---  Swift is a programming language for iOS and OS X development created by Apple. Designed to coexist with Objective-C and to be more resilient against erroneous code, Swift was introduced in 2014 at Apple's developer conference WWDC. It is built with the LLVM compiler included in Xcode 6 beta. +The official [Swift Programming Language](https://itunes.apple.com/us/book/swift-programming-language/id881256329) book from Apple is now available via iBooks. +  See also Apple's [getting started guide](https://developer.apple.com/library/prerelease/ios/referencelibrary/GettingStarted/LandingPage/index.html), which has a complete tutorial on Swift.  ```js  // -// Basics +// MARK: Basics  // +// Xcode supports landmarks to annotate your code and lists them in the jump bar +// MARK: Section mark +// TODO: Do something soon +// FIXME Fix this code +  println("Hello, world") +  var myVariable = 42 +let øπΩ = "value" // unicode variable names  let myConstant = 3.1415926 +let convenience = "keyword" // contextual variable name +let weak = "keyword"; let override = "another keyword" // statements can be separated by a semi-colon +let `class` = "keyword" // backticks allow keywords to be used as variable names  let explicitDouble: Double = 70 -let label = "some text " + String(myVariable)     // Casting -let piText = "Pi = \(myConstant)"                 // String interpolation -var optionalString: String? = "optional"          // Can be nil +let intValue = 0007 // 7 +let largeIntValue = 77_000 // 77000 +let label = "some text " + String(myVariable) // Casting +let piText = "Pi = \(myConstant), Pi 2 = \(myConstant * 2)" // String interpolation +var optionalString: String? = "optional" // Can be nil  optionalString = nil +/* +Comment here +    /* +        Nested comments are also supported +    */ +*/  // -// Arrays and Dictionaries +// MARK: Collections  //  // Array @@ -35,97 +56,108 @@ let emptyArray = [String]()  // Dictionary  var occupations = [ -  "Malcolm": "Captain", -  "kaylee": "Mechanic" +    "Malcolm": "Captain", +    "kaylee": "Mechanic"  ]  occupations["Jayne"] = "Public Relations"  let emptyDictionary = [String: Float]()  // -// Control Flow +// MARK: Control Flow  //  // for loop (array)  let myArray = [1, 1, 2, 3, 5]  for value in myArray { -  if value == 1 { -    println("One!") -  } else { -    println("Not one!") -  } +    if value == 1 { +        println("One!") +    } else { +        println("Not one!") +    }  }  // for loop (dictionary) +var dict = ["one": 1, "two": 2]  for (key, value) in dict { -  println("\(key): \(value)") +    println("\(key): \(value)")  }  // for loop (range)  for i in -1...1 { // [-1, 0, 1] -  println(i) +    println(i)  }  // use ..< to exclude the last number  // while loop  var i = 1  while i < 1000 { -  i *= 2 +    i *= 2  }  // do-while loop  do { -  println("hello") +    println("hello")  } while 1 == 2  // Switch  let vegetable = "red pepper"  switch vegetable {  case "celery": -  let vegetableComment = "Add some raisins and make ants on a log." +    let vegetableComment = "Add some raisins and make ants on a log."  case "cucumber", "watercress": -  let vegetableComment = "That would make a good tea sandwich." +    let vegetableComment = "That would make a good tea sandwich."  case let x where x.hasSuffix("pepper"): -  let vegetableComment = "Is it a spicy \(x)?" +    let vegetableComment = "Is it a spicy \(x)?"  default: // required (in order to cover all possible input) -  let vegetableComment = "Everything tastes good in soup." +    let vegetableComment = "Everything tastes good in soup."  }  // -// Functions +// MARK: Functions  //  // Functions are a first-class type, meaning they can be nested  // in functions and can be passed around -// Function +// Function with Swift header docs (format as reStructedText) +/** +    A greet operation + +    - A bullet in docs +    - Another bullet in the docs + +    :param: name A name +    :param: day A day +    :returns: A string containing the name and day value. +*/  func greet(name: String, day: String) -> String { -  return "Hello \(name), today is \(day)." +    return "Hello \(name), today is \(day)."  }  greet("Bob", "Tuesday")  // Function that returns multiple items in a tuple  func getGasPrices() -> (Double, Double, Double) { -  return (3.59, 3.69, 3.79) +    return (3.59, 3.69, 3.79)  } -// Args +// Variadic Args  func setup(numbers: Int...) {}  // Passing and returning functions  func makeIncrementer() -> (Int -> Int) { -  func addOne(number: Int) -> Int { -    return 1 + number -  } -  return addOne +    func addOne(number: Int) -> Int { +        return 1 + number +    } +    return addOne  }  var increment = makeIncrementer()  increment(7)  // -// Closures +// MARK: Closures  //  var numbers = [1, 2, 6] @@ -135,93 +167,243 @@ var numbers = [1, 2, 6]  // `->` separates the arguments and return type  // `in` separates the closure header from the closure body  numbers.map({ -  (number: Int) -> Int in -  let result = 3 * number -  return result -  }) +    (number: Int) -> Int in +    let result = 3 * number +    return result +})  // When the type is known, like above, we can do this  numbers = numbers.map({ number in 3 * number }) -//Or even this +// Or even this  //numbers = numbers.map({ $0 * 3 })  print(numbers) // [3, 6, 18] +// Trailing closure +numbers = sorted(numbers) { $0 > $1 } + +print(numbers) // [18, 6, 3] + +// Super shorthand, since the < operator infers the types + +numbers = sorted(numbers, < ) + +print(numbers) // [3, 6, 18]  // -// Classes +// MARK: Structures  // +// Structures and classes have very similar capabilites +struct NamesTable { +    let names: [String] + +    // Custom subscript +    subscript(index: Int) -> String { +        return names[index] +    } +} + +// Structures have an auto-generated (implicit) designated initializer +let namesTable = NamesTable(names: ["Me", "Them"]) +//let name = namesTable[2] +//println("Name is \(name)") // Name is Them + +// +// MARK: Classes +// + +// Classes, structures and its members have three levels of access control +// They are: internal (default), public, private + +public class Shape { +    public func getArea() -> Int { +        return 0; +    } +} +  // All methods and properties of a class are public.  // If you just need to store data in a  // structured object, you should use a `struct` -// A simple class `Square` extends `Shape` -class Square: Shape { -  var sideLength: Int = 1 +internal class Rect: Shape { +    var sideLength: Int = 1 +     +    // Custom getter and setter property +    private var perimeter: Int { +        get { +            return 4 * sideLength +        } +        set { +            // `newValue` is an implicit variable available to setters +            sideLength = newValue / 4 +        } +    } -  // Custom getter and setter property -  var perimeter: Int { -    get { -      return 4 * sideLength +    // Lazily load a property +    // subShape remains nil (uninitialized) until getter called +    lazy var subShape = Rect(sideLength: 4) +     +    // If you don't need a custom getter and setter, +    // but still want to run code before and after getting or setting +    // a property, you can use `willSet` and `didSet` +    var identifier: String = "defaultID" { +        // the `willSet` arg will be the variable name for the new value +        willSet(someIdentifier) { +            print(someIdentifier) +        }      } -    set { -      sideLength = newValue / 4 +     +    init(sideLength: Int) { +        super.init() +        self.sideLength = sideLength      } -  } - -  init(sideLength: Int) { -    super.init() -    self.sideLength = sideLength -  } - -  func shrink() { -    if sideLength > 0 { -      --sideLength +     +    func shrink() { +        if sideLength > 0 { +            --sideLength +        } +    } +     +    override func getArea() -> Int { +        return sideLength * sideLength      } -  } +} -  override func getArea() -> Int { -    return sideLength * sideLength -  } +// A simple class `Square` extends `Rect` +class Square: Rect { +    convenience init() { +        self.init(sideLength: 5) +    }  } -var mySquare = new Square(sideLength: 5) + +var mySquare = Square()  print(mySquare.getArea()) // 25  mySquare.shrink()  print(mySquare.sideLength) // 4 -// If you don't need a custom getter and setter, -// but still want to run code before and after getting or setting -// a property, you can use `willSet` and `didSet` +// compare instances, not the same as == which compares objects (equal to) +if mySquare === mySquare { +    println("Yep, it's mySquare") +}  // -// Enums +// MARK: Enums  //  // Enums can optionally be of a specific type or on their own.  // They can contain methods like classes.  enum Suit { -  case Spades, Hearts, Diamonds, Clubs -  func getIcon() -> String { -    switch self { -    case .Spades: return "♤" -    case .Hearts: return "♡" -    case .Diamonds: return "♢" -    case .Clubs: return "♧" +    case Spades, Hearts, Diamonds, Clubs +    func getIcon() -> String { +        switch self { +        case .Spades: return "♤" +        case .Hearts: return "♡" +        case .Diamonds: return "♢" +        case .Clubs: return "♧" +        }      } -  }  }  // -// Other +// MARK: Protocols +// + +// `protocol`s can require that conforming types have specific +// instance properties, instance methods, type methods,  +// operators, and subscripts. + +protocol ShapeGenerator { +    var enabled: Bool { get set } +    func buildShape() -> Shape +} + +/* +// Protocols declared with @objc allow optional functions, +// which allow you to check for conformance +@objc protocol TransformShape { +    optional func reshaped() +    optional func canReshape() -> Bool +} + +class MyShape: Rect { +    var delegate: TransformShape? + +    func grow() { +        sideLength += 2 + +        if let allow = self.delegate?.canReshape?() { +            // test for delegate then for method +            self.delegate?.reshaped?() +        } +    } +} +*/ + +// +// MARK: Other  // -// `protocol`: Similar to Java interfaces. -// `extension`s: Add extra functionality to an already created type +// `extension`s: Add extra functionality to an already existing type + +// Square now "conforms" to the `Printable` protocol +extension Square: Printable { +    var description: String { +        return "Area: \(self.getArea()) - ID: \(self.identifier)" +    } +} + +println("Square: \(mySquare)") + +// You can also extend built-in types +extension Int { +    var customProperty: String { +        return "This is \(self)" +    } + +    func multiplyBy(num: Int) -> Int { +        return num * self +    } +} + +println(7.customProperty) // "This is 7" +println(14.multiplyBy(2)) // 42 +  // Generics: Similar to Java. Use the `where` keyword to specify the  //   requirements of the generics. +func findIndex<T: Equatable>(array: [T], valueToFind: T) -> Int? { +    for (index, value) in enumerate(array) { +        if value == valueToFind { +            return index +        } +    } +    return nil +} +let foundAtIndex = findIndex([1, 2, 3, 4], 3) +println(foundAtIndex == 2) // true + +// Operators: +// Custom operators can start with the characters: +//      / = - + * % < > ! & | ^ . ~ +// or +// Unicode math, symbol, arrow, dingbat, and line/box drawing characters. +prefix operator !!! {} + +// A prefix operator that triples the side length when used +prefix func !!! (inout shape: Square) -> Square { +    shape.sideLength *= 3 +    return shape +} + +// current value +println(mySquare.sideLength) // 4 + +// change side length using custom !!! operator, increases size by 3 +!!!mySquare +println(mySquare.sideLength) // 12 +  ``` | 
