首页 > 代码库 > "Swift"编程语言
"Swift"编程语言
来自英文文档、百度翻译以及自己没过4级的渣渣英语功底,为了自己以后看起来方便
About Swift
关于"海燕"
IMPORTANT
重要
This is a preliminary document for an API or technology in development. Apple is supplying this information to help you plan for the adoption of the technologies and programming interfaces described herein for use on Apple-branded products. This information is subject to change, and software implemented according to this document should be tested with final operating system software and final documentation. Newer versions of this document may be provided with future seeds of the API or technology.
这是一个用于开发的API和技术的初期文档。
苹果公司正在提供这些信息来帮助你把这项技术和编程接口应用到你的苹果品牌产品中。
这些信息是随时变化的,根据这个文档实现的软件须要在终于的操作系统软件和终于文档上測试。新版本号的文档将会提供API和这项技术的未来种子(= =没翻译明确)。
Swift is a new programming language for iOS and OS X apps that builds on the best of C and Objective-C, without the constraints of C compatibility. Swift adopts safe programming patterns and adds modern features to make programming easier, more flexible, and more fun. Swift’s clean slate, backed by the mature and much-loved Cocoa and Cocoa Touch frameworks, is an opportunity to reimagine how software development works.
"海燕"是一个建立在C和Objective-C基础上。没有C语言兼容性约束的用于开发IOS和OS X操作系统应用的新语言。
"海燕"採用安全编程方式,加入了现代特征来使编程变得更简单,更灵活,更有趣。
"海燕"清白的历史,在成熟的受欢迎的Cocoa和Cocoa Touch框架的支持下,这在软件开发工作中是一个多么充满机遇的构想。
Swift has been years in the making. Apple laid the foundation for Swift by advancing our existing compiler, debugger, and framework infrastructure. We simplified memory management with Automatic Reference Counting (ARC). Our framework stack, built on the solid base of Foundation and Cocoa, has been modernized and standardized throughout. Objective-C itself has evolved to support blocks, collection literals, and modules, enabling framework adoption of modern language technologies without disruption. Thanks to this groundwork, we can now introduce a new language for the future of Apple software development.
"海燕"已经酝酿多年。
苹果公司提出这个"海燕"语言基础来推进已经存在的编译器。调试器和基础架构。我们使用ARC来使内存管理变得简单。
我们建立在Foundation和Cocoa基础上的框架层,已经现代化和规范化。Objective-C本身已经发展到支持代码块,容器,单元模块,这使不间断的採用现代语言成为可能。(是这个意思吧?= =)多亏于这个基础。我们如今能够为苹果软件开发的将来引入这样一个新语言。
Swift feels familiar to Objective-C developers. It adopts the readability of Objective-C’s named parameters and the power of Objective-C’s dynamic object model. It provides seamless access to existing Cocoa frameworks and mix-and-match interoperability with Objective-C code. Building from this common ground, Swift introduces many new features and unifies the procedural and object-oriented portions of the language.
Objective-C的开发人员会对于"雨燕"感到熟悉。"雨燕"基于易读的Objective-C的命名參数和Objective-C动态对象模式的动力。
它能够无缝的连接到已经存在的Cocoa框架并支持和Objective-C的混编。基于这些共同点。"雨燕"引入了很多特性、结合程序和语言的面向对象部分。(这里断句断不明确了= =)
Swift is friendly to new programmers. It is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language. It supports playgrounds, an innovative feature that allows programmers to experiment with Swift code and see the results immediately, without the overhead of building and running an app.
"雨燕"(下面直接称为"swift")对新的编程人员是友善的。
这是第一个工业质量(不懂= =)级别的系统编程语言。它像一个脚本语言一样富有表现力和有趣味。它支持的playgrounds,是一个革新性的特性,它同意程序猿在编写swift代码的同一时候立马看到那些结果,没有建立和执行一个应用程序的开销。
Swift combines the best in modern language thinking with wisdom from the wider Apple engineering culture. The compiler is optimized for performance, and the language is optimized for development, without compromising on either. It’s designed to scale from “hello, world” to an entire operating system. All this makes Swift a sound future investment for developers and for Apple.
swift运用最好的现代语言思想来思考苹果编程文化中的智慧。编译器的性能更优,语言的开发更优。这两者的提升不放弃当中一项。它的设计从"hello,world"一直衡量到整个操作系统。全部这些使得swift成为一个对于开发人员和对于苹果来说都是一个健康的未来。(应该就是你选择它不会错的意思= =)
Swift is a fantastic way to write iOS and OS X apps, and will continue to evolve with new features and capabilities. Our goals for Swift are ambitious. We can’t wait to see what you create with it.
swift是一个作为开发IOS和 OS X应用程序非常好的方式。而且它会继续开发新的特性和能力。我们的目标是雄心壮志的swift,我们迫不及待的想看到你创建出一个什么样的它。
A Swift Tour
一次雨燕之旅
println(Hello, world)
main
function. You also don’t need to write semicolons at the end of every statement.你相同不须要在每一个语句后面写分号。
假设你看不懂当中的一些,(没关系,)在本节中引出的全部东西。都会在这本书的其余部分详解。
Simple Values
let
to make a constant and var
to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.一个常量的值不须要在编译的时候被知道,但它必须被赋值过一次。这意味着你能够仅仅将常量赋值一次但能够在多处使用。
var myVariable = 42 myVariable = 50 let myConstant = 42
A constant or variable must have the same type as the value you want to assign to it. However, you don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type. In the example above, the compiler infers that
myVariable
is an integer because its initial value is a integer.然后,你不用一定要明白的写出类型。当你建立一个常量或变量时。你提供一个值来让编译器判断它的类型。在上面的样例中,编译器会判断出myVariable是一个整形。由于它被赋值了一个整形。
开。
let implicitInteger = 70 let implicitDouble = 70.0 let explicitDouble: Double = 70
EXPERIMENT
let label = "The width is " let width = 94 let widthLabel = label + String(width)
EXPERIMENT
String
from the last line. What error do you get?\
) before the parentheses. For example:let apples = 3 let oranges = 5 let appleSummary = "I have \(apples) apples." let fruitSummary = "I have \(apples + oranges) pieces of fruit."
\()
to include a floating-point calculation in a string and to include someone’s name in a greeting.[]
), and access their elements by writing the index or key in brackets.var shoppingList = ["catfish", "water", "tulips", "blue paint"] shoppingList[1] = "bottle of water" var occupations = [ "Malcolm": "Captain", "Kaylee": "Mechanic", ] occupations["Jayne"] = "Public Relations"
To create an empty array or dictionary, use the initializer syntax.
let emptyArray = String[]() let emptyDictionary = Dictionary<String, Float>()
type information can be inferred, you can write an empty array as
[]
and an empty dictionary as [:]
—for example, when you set a new value for a variable or pass an argument to a function.shoppingList = [] // Went shopping and bought everything.
Control Flow
if
and switch
to make conditionals, and use for
-in
, for
, while
, and do
-while
to make loops. Parentheses around the condition or loop variable are optional. Braces around the body are required.包围条件或者循环变量的圆括号是可选的。身体周围的大括号是必须的。
let individualScores = [75, 43, 103, 87, 12] var teamScore = 0 for score in individualScores { if score > 50 { teamScore += 3 } else { teamScore += 1 } } teamScore
In an
if
statement, the conditional must be a Boolean expression—this means that code such as if score { ... }
is an error, not an implicit comparison to zero.if
and let
together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil
to indicate that the value is missing. Write a question mark (?
) after the type of a value to mark the value as optional.在值的类型后面写一个问号标记(?)该值的类型可选。
var optionalString: String? = "Hello" optionalString == nil var optionalName: String? = "John Appleseed" var greeting = "Hello!" if let name = optionalName { greeting = "Hello, \(name)" }
optionalName
to nil
. What greeting do you get? Add an else
clause that sets a different greeting if optionalName
is nil
.nil
, the conditional is false
and the code in braces is skipped. Otherwise, the optional value is unwrapped and assigned to the constant after let
, which makes the unwrapped value available inside the block of code.否则,let后面的指定的可变值被赋值为这个常量,这使得被指定的值可用并进入大括号里的代码。
let vegetable = "red pepper" switch vegetable { case "celery": let vegetableComment = "Add some raisins and make ants on a log." case "cucumber", "watercress": let vegetableComment = "That would make a good tea sandwich." case let x where x.hasSuffix("pepper"): let vegetableComment = "Is it a spicy \(x)?" default: let vegetableComment = "Everything tastes good in soup." }
运行的状态不会继续到下一个分支。所以不须要在每个case代码的后面确切的标注退出switch。
for
-in
to iterate over items in a dictionary by providing a pair of names to use for each key-value pair.let interestingNumbers = [ "Prime": [2, 3, 5, 7, 11, 13], "Fibonacci": [1, 1, 2, 3, 5, 8], "Square": [1, 4, 9, 16, 25], ] var largest = 0 for (kind, numbers) in interestingNumbers { for number in numbers { if number > largest { largest = number } } } largest
while
to repeat a block of code until a condition changes. The condition of a loop can be at the end instead, ensuring that the loop is run at least once.var n = 2 while n < 100 { n = n * 2 } n var m = 2 do { m = m * 2 } while m < 100 m
You can keep an index in a loop—either by using
..
to make a range of indexes or by writing an explicit initialization, condition, and increment. These two loops do the same thing:var firstForLoop = 0 for i in 0..3 { firstForLoop += i } firstForLoop var secondForLoop = 0 for var i = 0; i < 3; ++i { secondForLoop += 1 } secondForLoopUse
..
to make a range that omits its upper value, and use ...
to make a range that includes both values.Functions and Closures
func
to declare a function. Call a function by following its name with a list of arguments in parentheses. Use ->
to separate the parameter names and types from the function’s return type.func greet(name: String, day: String) -> String { return "Hello \(name), today is \(day)." } greet("Bob", "Tuesday")
Remove the
day
parameter. Add a parameter to include today’s lunch special in the greeting.func getGasPrices() -> (Double, Double, Double) { return (3.59, 3.69, 3.79) } getGasPrices()
Functions can also take a variable number of arguments, collecting them into an array.
func sumOf(numbers: Int...) -> Int { var sum = 0 for number in numbers { sum += number } return sum } sumOf() sumOf(42, 597, 12)
在函数过长或者非常复杂的时候,你能够使用嵌套函数来组织代码。
func returnFifteen() -> Int { var y = 10 func add() { y += 5 } add() return y } returnFifteen()
Functions are a first-class type. This means that a function can return another function as its value.
func makeIncrementer() -> (Int -> Int) { func addOne(number: Int) -> Int { return 1 + number } return addOne } var increment = makeIncrementer() increment(7)
A function can take another function as one of its arguments.
func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool { for item in list { if condition(item) { return true } } return false } func lessThanTen(number: Int) -> Bool { return number < 10 } var numbers = [20, 19, 7, 12] hasAnyMatches(numbers, lessThanTen)
Functions are actually a special case of closures. You can write a closure without a name by surrounding code with braces (
{}
). Use in
to separate the arguments and return type from the body.你能够写一个被大括号{}包裹着的没有名字的匿名方法。在函数体中使用in来分隔參数和返回值。
numbers.map({ (number: Int) -> Int in let result = 3 * number return result })
Rewrite the closure to return zero for all odd numbers.
当一个闭包的类型已知时,就像一个代理的回调。你能够省略它们的參数类型,它们的返回值,或者都省略。一个简单的闭包声明只隐式的返回它们声明的返回值。
numbers.map({ number in 3 * number })
。)
sort([1, 5, 3, 12, 2]) { $0 > $1 }
Objects and Classes
class
followed by the class’s name to create a class. A property declaration in a class is written the same way as a constant or variable declaration, except that it is in the context of a class. Likewise, method and function declarations are written the same way.类中的属性的声明方式和一个变量或常量的声明一样。除非它在类的上下文中。相同的,方法和函数的声明也都相同。
class Shape { var numberOfSides = 0 func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } }
Add a constant property with
let
, and add another method that takes an argument.var shape = Shape() shape.numberOfSides = 7 var shapeDescription = shape.simpleDescription()
This version of the
Shape
class is missing something important: an initializer to set up the class when an instance is created. Use init
to create one.class NamedShape { var numberOfSides: Int = 0 var name: String init(name: String) { self.name = name } func simpleDescription() -> String { return "A shape with \(numberOfSides) sides." } }
Notice how
self
is used to distinguish the name
property from the name
argument to the initializer. The arguments to the initializer are passed like a function call when you create an instance of the class. Every property needs a value assigned—either in its declaration (as with numberOfSides
) or in the initializer (as with name
).当你创建一个类的实例时。这些參数对于构造器像一个函数一样被调用。每个属性须要被数值。在它被声明的时候(像numberOfSides)或该类初始化的时候(像name)。
deinit
to create a deinitializer if you need to perform some cleanup before the object is deallocated.不要求子类必须继承一个标准的根类。所以你能够按需包括一个父类或省略它。
override
—overriding a method by accident, without override
, is detected by the compiler as an error. The compiler also detects methods with override
that don’t actually override any method in the superclass.class Square: NamedShape { var sideLength: Double init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 4 } func area() -> Double { return sideLength * sideLength } override func simpleDescription() -> String { return "A square with sides of length \(sideLength)." } } let test = Square(sideLength: 5.2, name: "my test square") test.area() test.simpleDescription()
NamedShape
called Circle
that takes a radius and a name as arguments to its initializer. Implement an area
and a describe
method on the Circle
class.class EquilateralTriangle: NamedShape { var sideLength: Double = 0.0 init(sideLength: Double, name: String) { self.sideLength = sideLength super.init(name: name) numberOfSides = 3 } var perimeter: Double { get { return 3.0 * sideLength } set { sideLength = newValue / 3.0 } } override func simpleDescription() -> String { return "An equilateral triagle with sides of length \(sideLength)." } } var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle") triangle.perimeter triangle.perimeter = 9.9 triangle.sideLength
In the setter for
perimeter
, the new value has the implicit name newValue
. You can provide an explicit name in parentheses after set
.Notice that the initializer for the EquilateralTriangle
class has three different steps:
Setting the value of properties that the subclass declares.
Calling the superclass’s initializer.
Changing the value of properties defined by the superclass. Any additional setup work that uses methods, getters, or setters can also be done at this point.
willSet
and didSet
. For example, the class below ensures that the side length of its triangle is always the same as the side length of its square.class TriangleAndSquare { var triangle: EquilateralTriangle { willSet { square.sideLength = newValue.sideLength } } var square: Square { willSet { triangle.sideLength = newValue.sideLength } } init(size: Double, name: String) { square = Square(sideLength: size, name: name) triangle = EquilateralTriangle(sideLength: size, name: name) } } var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape") triangleAndSquare.square.sideLength triangleAndSquare.triangle.sideLength triangleAndSquare.square = Square(sideLength: 50, name: "larger square") triangleAndSquare.triangle.sideLength
class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes times: Int) { count += amount * times } } var counter = Counter() counter.incrementBy(2, numberOfTimes: 7)
?
before operations like methods, properties, and subscripting. If the value before the ?
is nil
, everything after the ?
is ignored and the value of the whole expression is nil
. Otherwise, the optional value is unwrapped, and everything after the ?
acts on the unwrapped value. In both cases, the value of the whole expression is an optional value.不管如何。这个表达式的值都是一个可变值。
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength
Enumerations and Structures
enum
to create an enumeration. Like classes and all other named types, enumerations can have methods associated with them.enum Rank: Int { case Ace = 1 case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpleDescription() -> String { switch self { case .Ace: return "ace" case .Jack: return "jack" case .Queen: return "queen" case .King: return "king" default: return String(self.toRaw()) } } } let ace = Rank.Ace let aceRawValue = http://www.mamicode.com/ace.toRaw()
EXPERIMENT
Rank
values by comparing their raw values.Int
, so you only have to specify the first raw value. The rest of the raw values are assigned in order. You can also use strings or floating-point numbers as the raw type of an enumeration.toRaw
and fromRaw
functions to convert between the raw value and the enumeration value.if let convertedRank = Rank.fromRaw(3) { let threeDescription = convertedRank.simpleDescription() }
The member values of an enumeration are actual values, not just another way of writing their raw values. In fact, in cases where there isn’t a meaningful raw value, you don’t have to provide one.
其实,没有一个有意义的原始值,你不须要提供一个。
enum Suit { case Spades, Hearts, Diamonds, Clubs func simpleDescription() -> String { switch self { case .Spades: return "spades" case .Hearts: return "hearts" case .Diamonds: return "diamonds" case .Clubs: return "clubs" } } } let hearts = Suit.Hearts let heartsDescription = hearts.simpleDescription()
Add a
color
method to Suit
that returns “black” for spades and clubs, and returns “red” for hearts and diamonds.Hearts
member of the enumeration is referred to above: When assigning a value to the hearts
constant, the enumeration member Suit.Hearts
is referred to by its full name because the constant doesn’t have an explicit type specified. Inside the switch, the enumeration is referred to by the abbreviated form .Hearts
because the value of self
is already known to be a suit. You can use the abbreviated form anytime the value’s type is already known.struct
to create a structure. Structures support many of the same behaviors as classes, including methods and initializers. One of the most important differences between structures and classes is that structures are always copied when they are passed around in your code, but classes are passed by reference.结构体同类一样支持非常多的行为,包含方法和构造器。结构体和类的一个最大的差别在于当结构体被调用到你的代码时。他们都是复制过来的,而类仅仅是传递引用。
struct Card { var rank: Rank var suit: Suit func simpleDescription() -> String { return "The \(rank.simpleDescription()) of \(suit.simpleDescription())" } } let threeOfSpades = Card(rank: .Three, suit: .Spades) let threeOfSpadesDescription = threeOfSpades.simpleDescription()
Add a method to
Card
that creates a full deck of cards, with one card of each combination of rank and suit.当你创建这个实例时提供相关值。相关值和初始值是不同的。一个枚举成员的初始值对于全部它的实例都是同样的。而且是你在定义这个枚举类型时提供的。
enum ServerResponse { case Result(String, String) case Error(String) } let success = ServerResponse.Result("6:00 am", "8:09 pm") let failure = ServerResponse.Error("Out of cheese.") switch success { case let .Result(sunrise, sunset): let serverResponse = "Sunrise is at \(sunrise) and sunset is at \(sunset)." case let .Error(error): let serverResponse = "Failure... \(error)" }
Add a third case to
ServerResponse
and to the switch.ServerResponse
value as part of matching the value against the switch cases.Protocols and Extensions
protocol
to declare a protocol.protocol ExampleProtocol { var simpleDescription: String { get } mutating func adjust() }
Classes, enumerations, and structs can all adopt protocols.
class SimpleClass: ExampleProtocol { var simpleDescription: String = "A very simple class." var anotherProperty: Int = 69105 func adjust() { simpleDescription += " Now 100% adjusted." } } var a = SimpleClass() a.adjust() let aDescription = a.simpleDescription struct SimpleStructure: ExampleProtocol { var simpleDescription: String = "A simple structure" mutating func adjust() { simpleDescription += " (adjusted)" } } var b = SimpleStructure() b.adjust() let bDescription = b.simpleDescription
mutating
keyword in the declaration of SimpleStructure
to mark a method that modifies the structure. The declaration of SimpleClass
doesn’t need any of its methods marked as mutating because methods on a class can always modify the class.extension
to add functionality to an existing type, such as new methods and computed properties. You can use an extension to add protocol conformance to a type that is declared elsewhere, or even to a type that you imported from a library or framework.extension Int: ExampleProtocol { var simpleDescription: String { return "The number \(self)" } mutating func adjust() { self += 42 } } 7.simpleDescription
Write an extension for the
Double
type that adds an absoluteValue
property.当你使用一种被定义为协议类型的类型的值时,那么定义在协议外面的方法将不可用。
let protocolValue: ExampleProtocol = a protocolValue.simpleDescription // protocolValue.anotherProperty // Uncomment to see the error
Even though the variable
protocolValue
has a runtime type of SimpleClass
, the compiler treats it as the given type of ExampleProtocol
. This means that you can’t accidentally access methods or properties that the class implements in addition to its protocol conformance.Generics
func repeat<ItemType>(item: ItemType, times: Int) -> ItemType[] { var result = ItemType[]() for i in 0..times { result += item } return result } repeat("knock", 4)
// Reimplement the Swift standard library's optional type enum OptionalValue<T> { case None case Some(T) } var possibleInteger: OptionalValue<Int> = .None possibleInteger = .Some(100)
Use
where
after the type name to specify a list of requirements—for example, to require the type to implement a protocol, to require two types to be the same, or to require a class to have a particular superclass.func anyCommonElements <T, U where T: Sequence, U: Sequence, T.GeneratorType.Element: Equatable, T.GeneratorType.Element == U.GeneratorType.Element> (lhs: T, rhs: U) -> Bool { for lhsItem in lhs { for rhsItem in rhs { if lhsItem == rhsItem { return true } } } return false } anyCommonElements([1, 2, 3], [3])
Modify the
anyCommonElements
function to make a function that returns an array of the elements that any two sequences have in common.where
and simply write the protocol or class name after a colon. Writing<T: Equatable>
is the same as writing <T where T: Equatable>
.虽然如此。swift的很多部分将会和你所掌握的C和Objective-C语言非常相似。
Int
for integers; Double
and Float
for floating-point values; Bool
for Boolean values; and String
for textual data. Swift also provides powerful versions of the two primary collection types, Array
and Dictionary
, as described in Collection Types.Bool相应Boolean值,和String相应文本数据。swift相同提供了强有力的版本号相应两个基本的集合类型。Array和Dictionary。
swift相同广泛的使用那些不能被改变值的变量。这些被叫做常量,而且不在C中更加的强大。
当你使用一个值单并不须要改变它时,常量被贯穿始终使的代码更加的安全和干净。
元组能够从一个函数中返回多个值就像一个单独的复合的值。
nil
with pointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than nil
pointers in Objective-C and are at the heart of many of Swift’s most powerful features.String
, type safety prevents you from passing it an Int
by mistake. This enables you to catch and fix errors as early as possible in the development process."Swift"编程语言