本文是學(xué)習(xí)《The Swift Programming Language》整理的相關(guān)隨筆幢哨,基本的語法不作介紹奸焙,主要介紹Swift中的一些特性或者與OC差異點津坑。
系列文章:
Generic Collections
Swift’s array, set, and dictionary types are implemented
as generic collections. For more on generic types and
collections, see Generics.
- Swift中集合的實現(xiàn)都使用到泛型的概念黄选。
Mutability of Collections
If you create an array, a set, or a dictionary, and assign
it to a variable, the collection that is created will be
mutable. This means that you can change (or mutate) the
collection after it is created by adding, removing, or changing items in the collection. If you assign an array,
a set, or a dictionary to a constant, that collection is
immutable, and its size and contents cannot be changed.
- Swift中集合用
let
修飾的就是不可變集合知纷,var
修飾的就是可變集合。
例子:
let threeDoubles = Array(repeatElement(0.0, count: 3));
threeDoubles.append(1.0);
編譯失敿锌住:
MyPlayground.playground:146:1: note: change 'let' to 'var'
to make it mutable
let threeDoubles = Array(repeatElement(0.0, count: 3));
^~~
var
Arrays
Array Type Shorthand Syntax
The type of a Swift array is written in full as
Array<Element>, where Element is the type of values the
array is allowed to store. You can also write the type of
an array in shorthand form as [Element]. Although the two
forms are functionally identical, the shorthand form is
preferred and is used throughout this guide when referring
to the type of an array.
- Swift集合數(shù)組的存在兩種方式的寫法被盈,推薦使用[Element]的方式。
例子:
var someInts = [Int]();
print("someInts \(someInts.count)");
var otherSomeInts = Array<Int>();
print("someInts \(otherSomeInts.count)");
Iterating Over an Array
以下兩種方式都可以使用搭伤,特別說明第二種每次遍歷拿到的是一個元組(index,value)只怎。
例子:
var colors = ["red","green","yellow"];
for color in colors{
print("color:\(color)");
}
for (index,color) in colors.enumerated(){
print("index:\(index),color:\(color)");
}
執(zhí)行結(jié)果:
color:red
color:green
color:yellow
index:0,color:red
index:1,color:green
index:2,color:yellow
Sets
Hash Values for Set Types
A type must be hashable in order to be stored in a set—
that is, the type must provide a way to compute a hash
value for itself. A hash value is an Int value that is the
same for all objects that compare equally, such that if a
== b, it follows that a.hashValue == b.hashValue.
- Swift中的Sets設(shè)計與OC中都一樣需要通過
hash
值來與其他的存儲數(shù)據(jù)進(jìn)行比較。
Dictionaries
Creating a Dictionary with a Dictionary Literal
A key-value pair is a combination of a key and a value. In
a dictionary literal, the key and value in each key-value
pair are separated by a colon. The key-value pairs are
written as a list, separated by commas, surrounded by a
pair of square brackets:
[key 1: value 1, key 2: value 2, key 3: value 3]
- 與OC中字典的賦值存在不同格式怜俐,只是搞不懂通用的
{}
為什么Swift中不采用身堡,而是使用[]
(OC,js中都是{}的設(shè)計)佑菩。