"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
一次雨燕之旅
Swift, this can be done in a single line:
println(Hello, world)
program. You don’t need to import a separate library for functionality like input/output or string handling. Code written at global scope is used as the entry point for the program, so you don’t need a
main
function.You also don’t need to write semicolons at the end of every statement.
你相同不须要在每一个语句后面写分号。
tour gives you enough information to start writing code in Swift by showing you how to accomplish a variety of programming tasks. Don’t worry if you don’t understand something—everything introduced in this tour is explained in detail in the rest of this book.
假设你看不懂当中的一些,(没关系,)在本节中引出的全部东西。都会在这本书的其余部分详解。
the best experience, open this chapter as a playground in Xcode. Playgrounds allow you to edit the code listings and see the result immediately.
Simple Values
let
tomake a constant and
var
tomake 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是一个整形。由于它被赋值了一个整形。
the initial value doesn’t provide enough information (or if there is no initial value), specify the type by writing it after the variable, separated by a colon.
开。
let implicitInteger = 70
let implicitDouble = 70.0
let explicitDouble: Double = 70
EXPERIMENT
Create a constant with an explicit type of Float and a value of 4.
make an instance of the desired type.
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
EXPERIMENT
String
fromthe last line. What error do you get?
simpler way to include values in strings: Write the value in parentheses, and write a backslash (
\
)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."
\()
toinclude a floating-point calculation in a string and to include someone’s name in a greeting.
arrays and dictionaries using brackets (
[]
),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
tomake conditionals, and use
for
-in
, for
, while
,and
do
-while
tomake 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
is an error, not an implicit comparison to zero.
score { ... }
if
and let
togetherto work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains
nil
toindicate 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
clausethat sets a different greeting if
optionalName
is nil
.the optional value is
nil
,the conditional is
false
andthe 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后面的指定的可变值被赋值为这个常量,这使得被指定的值可用并进入大括号里的代码。
support any kind of data and a wide variety of comparison operations—they aren’t limited to integers and tests for equality.
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."
}
executing the code inside the switch case that matched, the program exits from the switch statement. Execution doesn’t continue to the next case, so there is no need to explicitly break out of the switch at the end of each case’s code.
运行的状态不会继续到下一个分支。所以不须要在每个case代码的后面确切的标注退出switch。
use
for
-in
toiterate 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
Add another variable to keep track of which kind of number was the largest, as well as what that largest number was.
while
torepeat 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
}
secondForLoop
Use ..
to
make a range that omits its upper value, and use ...
to
make a range that includes both values.
Functions and Closures
func
todeclare a function. Call a function by following its name with a list of arguments in parentheses. Use
->
toseparate 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.
a tuple to return multiple values from a function.
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)
Write a function that calculates the average of its arguments.
can be nested. Nested functions have access to variables that were declared in the outer function. You can use nested functions to organize the code in a function that is long or complex.
在函数过长或者非常复杂的时候,你能够使用嵌套函数来组织代码。
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.
closure’s type is already known, such as the callback for a delegate, you can omit the type of its parameters, its return type, or both. Single statement closures implicitly return the value of their only statement.
当一个闭包的类型已知时,就像一个代理的回调。你能够省略它们的參数类型,它们的返回值,或者都省略。一个简单的闭包声明只隐式的返回它们声明的返回值。
numbers.map({ number in 3 * number })
You can refer to parameters by number instead of by name—this approach is especially useful in very short closures. A closure passed as the last argument
to a function can appear immediately after the parentheses.
。)
sort([1, 5, 3, 12, 2]) { $0 > $1 }
Objects and Classes
class
followedby 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.
an instance of a class by putting parentheses after the class name. Use dot syntax to access the properties and methods of the instance.
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
tocreate a deinitializer if you need to perform some cleanup before the object is deallocated.
include their superclass name after their class name, separated by a colon. There is no requirement for classes to subclass any standard root class, so you can include or omit a superclass as needed.
不要求子类必须继承一个标准的根类。所以你能够按需包括一个父类或省略它。
override
—overridinga method by accident, without
override
,is detected by the compiler as an error. The compiler also detects methods with
override
thatdon’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()
Make another subclass of 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.
simple properties that are stored, properties can have a getter and a setter.
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.
注意,EquilateralTriangle在初始化的时候有三个不同的步骤:
need to compute the property but still need to provide code that is run before and after setting a new value, use
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
Methods on classes have one important difference from functions. Parameter names in functions are used only within the function, but parameters names
in methods are also used when you call the method (except for the first parameter). By default, a method has the same name for its parameters when you call it and within the method itself. You can specify a second name, which is used inside the method.
class Counter {
var count: Int = 0
func incrementBy(amount: Int, numberOfTimes times: Int) {
count += amount * times
}
}
var counter = Counter()
counter.incrementBy(2, numberOfTimes: 7)
working with optional values, you can write
?
beforeoperations like methods, properties, and subscripting. If the value before the
?
is nil
,everything after the
?
isignored and the value of the whole expression is
nil
.Otherwise, the optional value is unwrapped, and everything after the
?
actson 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
tocreate 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 = ace.toRaw()
EXPERIMENT
Write a function that compares two Rank
values
by comparing their raw values.
写一个函数通过比較两个Rank的初始值来比較他们。
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
functionsto 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.
the two ways that the
Hearts
memberof the enumeration is referred to above: When assigning a value to the
hearts
constant,the enumeration member
Suit.Hearts
isreferred 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
becausethe value of
self
isalready known to be a suit. You can use the abbreviated form anytime the value’s type is already known.
struct
tocreate 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.
member can have different values associated with them. You provide the associated values when you create the instance. Associated values and raw values are different: The raw value of an enumeration member is the same for all of its instances, and you provide
the raw value when you define the enumeration.
当你创建这个实例时提供相关值。相关值和初始值是不同的。一个枚举成员的初始值对于全部它的实例都是同样的。而且是你在定义这个枚举类型时提供的。
consider the case of requesting the sunrise and sunset time from a server. The server either responds with the information or it responds with some error information.
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.
how the sunrise and sunset times are extracted from the
ServerResponse
valueas part of matching the value against the switch cases.
case的一部分ServerResponse的值中获取的。
Protocols and Extensions
protocol
todeclare 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
Write an enumeration that conforms to this protocol.
mutating
keywordin the declaration of
SimpleStructure
tomark a method that modifies the structure. The declaration of
SimpleClass
doesn’tneed any of its methods marked as mutating because methods on a class can always modify the class.
extension
toadd 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.
to create a collection of objects that have different types but that all conform to a single protocol. When you work with values whose type is a protocol type, methods outside the protocol definition are not available.
当你使用一种被定义为协议类型的类型的值时,那么定义在协议外面的方法将不可用。
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)
make generic forms of functions and methods, as well as classes, enumerations, and structures.
// 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.
the simple cases, you can omit
where
andsimply write the protocol or class name after a colon. Writing
<T:
Equatable>
is the same as writing <T
where T: Equatable>
.X app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C.
虽然如此。swift的很多部分将会和你所掌握的C和Objective-C语言非常相似。
provides its own versions of all fundamental C and Objective-C types, including
Int
forintegers;
Double
and Float
forfloating-point values;
Bool
forBoolean values; and
String
fortextual 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。
variables whose values cannot be changed. These are known as constants, and are much more powerful than constants in C. Constants are used throughout Swift to make code safer and clearer in intent when you work with values that do not need to change.
swift相同广泛的使用那些不能被改变值的变量。这些被叫做常量,而且不在C中更加的强大。
当你使用一个值单并不须要改变它时,常量被贯穿始终使的代码更加的安全和干净。
to familiar types, Swift introduces advanced types not found in Objective-C. These include tuples, which enable you to create and pass around groupings of values. Tuples can return multiple values from a function as a single compound value.
元组能够从一个函数中返回多个值就像一个单独的复合的值。
also introduces optional types, which handle the absence of a value. Optionals say either “there is a
value, and it equals x”
or “there isn’t a
value at all”. Optionals are similar to using
nil
withpointers in Objective-C, but they work for any type, not just classes. Optionals are safer and more expressive than
nil
pointersin Objective-C and are at the heart of many of Swift’s most powerful features.
safe language. Swift helps you to be clear about the types of values your code can work with. If
part of your code expects a
String
,type safety prevents you from passing it an
Int
bymistake. This enables you to catch and fix errors as early as possible in the development process.
"Swift"编程语言的更多相关文章
- NYOJ 741 "数学家"ST
"数学家"ST 时间限制:1000 ms | 内存限制:65535 KB 难度:2 描写叙述 ST是个非常特别的人类,不仅喜欢做一些不同平常的事,并且对于在无聊的时候怎样打发时 ...
- 无法解决 equal to 运算中 "Chinese_PRC_CI_AS" 和 "SQL_Latin1_General_CP1_CI_AS" 之间的排序规则冲突。
什么是排序规则(collation) 关于SQL Server的排序规则,估计大家都不陌生,在创建数据库时我们经常要选择一种排序规则(conllation),一般我们会留意到每一种语言的排序规则都有许 ...
- C++11 之 " = delete "
1 缺省函数 设计一个类,没有成员函数 (member function),只有成员数据 (member data) class DataOnly { private: std::string st ...
- 谷歌技术"三宝"之MapReduce
江湖传说永流传:谷歌技术有"三宝",GFS.MapReduce和大表(BigTable)! 谷歌在03到06年间连续发表了三篇非常有影响力的文章,各自是03年SOSP的GFS,04 ...
- xcode 左边导航栏中,类文件后面的标记“A”,"M","?"……等符号的含义???
"M" = Locally modified "U" = Updated in repository "A" = Locally a ...
- 上struts2的xml在<result type="redirect">参数问题
今天做项目,我遇到了一个精彩的问题. 我需要在struts的xml中的<action>的<result>中配置type="redirect".同一时候须要传 ...
- Jquery中的事件绑定$("#btn").bind("click",function(){ })
Jquery中的事件绑定:$("#btn").bind("click",function(){ }) 由于每次都这么调用太麻烦,所以jquery就用$(&qu ...
- javascript正則表達式 "\b"问题
preface 昨晚在看<javascript权威指南>后.看见作者自己封装一个兼容全部浏览器的山寨HTML5新API classLIst类.自己想了想认为自己也要去玩一下.可是能力还是有 ...
- 设置android:supportsRtl="true"无效问题
今天解bug时,遇到这样一个问题: 问题描写叙述:切换系统语言为阿拉伯文时,actionbar布局没有变为从右向左排列. 于是,我在Androidmanifest.xml文件里的 appli ...
随机推荐
- JavaScript--模块化 JavaScript module designer
module: 模块就是实现特定功能的一组方法.1.在首页的一个接口js;首先下载好require.js文件引入首页. <script src="require.js" da ...
- BZOJ4372: 烁烁的游戏(动态点分治)
Description 背景:烁烁很喜欢爬树,这吓坏了树上的皮皮鼠.题意:给定一颗n个节点的树,边权均为1,初始树上没有皮皮鼠.烁烁他每次会跳到一个节点u,把周围与他距离不超过d的节点各吸引出w只皮皮 ...
- 洛谷—— P1190 接水问题
https://www.luogu.org/problem/show?pid=1190#sub 题目描述 学校里有一个水房,水房里一共装有 m 个龙头可供同学们打开水,每个龙头每秒钟的 供水量相等,均 ...
- 洛谷——V1772 巧妙填数
描述 将1,2,\cdots,91,2,⋯,9共99个数分成三组,分别组成三个三位数,且使这三个三位数构成1:2:31:2:3的比例. 试求出所有满足条件的三个三位数.例如:三个三位数192,384, ...
- Fiddler代理配置
1.下载安装软件Fiddler 2.Fiddler设置HTTPS代理(如果代理的是https请求的需要操作这一步) 打开Fiddler,菜单栏:Tools -> Fiddler Options ...
- Hadoop3.0配置
1.core-site.xml <configuration> <property> <name>fs.default.namenode</name> ...
- qemu 参数简介
参数 示例 说明 -hda -hda /data/windows.img 指定windows.img作为硬盘镜像 -cdrom -cdrom /data/windows.iso 指定windows.i ...
- vue项目对axios的全局配置
标准的vue-cli项目结构(httpConfig文件夹自己建的): api.js: //const apiUrl = 'http://test';//测试域名,自己改成自己的 const apiUr ...
- 【redis,1】java操作redis: 将string、list、map、自己定义的对象保存到redis中
一.操作string .list .map 对象 1.引入jar: jedis-2.1.0.jar 2.代码 /** * @param args */ public s ...
- java回调函数这样说,应该明确了吧!
有哥们问我回调怎么用,回调怎么理解? 怎么说好呢,仅仅可意会不可言传呐,非也,回调在实际开发中使用频率事实上是非常高的,恰好我小时候也被回调函数欺负过,居然问了,那么肯定要好好分享一下我的一些经验. ...