第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

swift 定義了數(shù)組 函數(shù)怎么使用

swift 定義了數(shù)組 函數(shù)怎么使用

達令說 2019-03-14 14:10:03
swift 定義了數(shù)組 函數(shù)怎么使用
查看完整描述

2 回答

?
RISEBY

TA貢獻1856條經(jīng)驗 獲得超5個贊

和其他對象一樣當做參數(shù)使用即可。比如:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

fun function(x: [Int]) {

  // 打印所有元素

  print(x)

   

  // 生成一個新數(shù)組,每個元素都是原數(shù)組的二倍

  let y = x.map { $0 * 2 }

  // 新數(shù)組結果應該是 [2, 4, 6, 8, 10]

  print(y)

   

  // 所有數(shù)組元素求和,0 表示初始化一個值為零的和變量

  let z = x.reduce(0) { $0 + $1 }

  // z 的結果應該是 1 + 2 + 3 + 4 + 5 = 15

  print(z)

}

 

let a = [1, 2, 3, 4, 5]

function(x: a)

 


查看完整回答
反對 回復 2019-03-22
?
慕桂英3389331

TA貢獻2036條經(jīng)驗 獲得超8個贊

Swift的數(shù)組是一個結構體類型,它遵守了CollectionType、MutableCollectionType、_DstructorSafeContainer協(xié)議,其中最重要的就是CollectionType協(xié)議,數(shù)組的一些主要功能都是通過這個協(xié)議實現(xiàn)的。而CollectionType協(xié)議又遵守Indexable和SequenceType這兩個協(xié)議。而在這兩個協(xié)議中,SequenceType協(xié)議是數(shù)組、字典等集合類型最重要的協(xié)議,在文檔中解釋了SequenceType是一個可以通過for...in循環(huán)迭代的類型,實現(xiàn)了這個協(xié)議,就可以for...in循環(huán)了。
A type that can be iterated with a for...in loop.
而SequenceType是建立在GeneratorType基礎上的,sequence需要GeneratorType來告訴它如何生成元素。
GeneratorType
GeneratorType協(xié)議有兩部分組成:
它需要有一個Element關聯(lián)類型,這也是它產(chǎn)生的值的類型。
它需要有一個next方法。這個方法返回Element的可選對象。通過這個方法就可以一直獲取下一個元素,直到返回nil,就意味著已經(jīng)獲取到了所有元素。
/// Encapsulates iteration state and interface for iteration over a
/// sequence.
///
/// - Note: While it is safe to copy a generator, advancing one
/// copy may invalidate the others.
///
/// Any code that uses multiple generators (or `for`...`in` loops)
/// over a single sequence should have static knowledge that the
/// specific sequence is multi-pass, either because its concrete
/// type is known or because it is constrained to `CollectionType`.
/// Also, the generators must be obtained by distinct calls to the
/// sequence's `generate()` method, rather than by copying.
public protocol GeneratorType {
/// The type of element generated by `self`.
associatedtype Element
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Requires: `next()` has not been applied to a copy of `self`
/// since the copy was made, and no preceding call to `self.next()`
/// has returned `nil`. Specific implementations of this protocol
/// are encouraged to respond to violations of this requirement by
/// calling `preconditionFailure("...")`.
@warn_unused_result
public mutating func next() -> Self.Element?
}
我把自己實現(xiàn)的數(shù)組命名為MYArray,generator為MYArrayGenerator,為了簡單,這里通過字典來存儲數(shù)據(jù),并約定字典的key為從0開始的連續(xù)數(shù)字。就可以這樣來實現(xiàn)GeneratorType:
/// 需保準dic的key是從0開始的連續(xù)數(shù)字
struct MYArrayGenerator<T>: GeneratorType {
private let dic: [Int: T]
private var index = 0
init(dic: [Int: T]) {
self.dic = dic
}
mutating func next() -> T? {
let element = dic[index]
index += 1
return element
}
}
這里通過next方法的返回值,隱式地為Element賦值。顯式地賦值可以這樣寫typealias Element = T。要使用這個生成器就非常簡單了:
let dic = [0: "XiaoHong", 1: "XiaoMing"]
var generator = MYArrayGenerator(dic: dic)
while let elment = generator.next() {
print(elment)
}
// 打印的結果:
// XiaoHong
// XiaoMing
SequenceType
有了generator,接下來就可以實現(xiàn)SequenceType協(xié)議了。SequenceType協(xié)議也是主要有兩部分:
需要有一個Generator關聯(lián)類型,它要遵守GeneratorType。
要實現(xiàn)一個generate方法,返回一個Generator。同樣的,我們可以通過制定generate方法的方法類型來隱式地設置Generator:
struct MYArray<T>: SequenceType {
private let dic: [Int: T]
func generate() -> MYArrayGenerator<T> {
return MYArrayGenerator(dic: dic)
}
}
這樣我們就可以創(chuàng)建一個MYArray實例,并通過for循環(huán)來迭代:
let dic = [0: "XiaoHong", 1: "XiaoMing", 2: "XiaoWang", 3: "XiaoHuang", 4: "XiaoLi"]
let array = MYArray(dic: dic)
for value in array {
print(value)
}
let names = array.map { $0 }
當然,目前這個實現(xiàn)還存在很大的隱患,因為傳入的字典的key是不可知的,雖然我們限定了必須是Int類型,但無法保證它一定是從0開始,并且是連續(xù),因此我們可以通過修改初始化方法來改進:
init(elements: T...) {
dic = [Int: T]()
elements.forEach { dic[dic.count] = $0 }
}
然后我們就可以通過傳入多參數(shù)來創(chuàng)建實例了:
let array = MYArray(elements: "XiaoHong", "XiaoMing", "XiaoWang", "XiaoHuang", "XiaoLi")
再進一步,通過實現(xiàn)ArrayLiteralConvertible協(xié)議,我們可以像系統(tǒng)的Array數(shù)組一樣,通過字面量來創(chuàng)建實例:
let array = ["XiaoHong", "XiaoMing", "XiaoWang", "XiaoHuang", "XiaoLi"]
最后還有一個數(shù)組的重要特性,就是通過下標來取值,這個特性我們可以通過實現(xiàn)subscript方法來實現(xiàn):
extension MYArray {
subscript(idx: Int) -> Element {
precondition(idx < dic.count, "Index out of bounds")
return dic[idx]!
}
}
print(array[3]) // XiaoHuang
至此,一個自定義的數(shù)組就基本實現(xiàn)了,我們可以通過字面量來創(chuàng)建一個數(shù)組,可以通過下標來取值,可以通過for循環(huán)來遍歷數(shù)組,可以使用map、forEach等高階函數(shù)。
小結
要實現(xiàn)一個數(shù)組的功能,主要是通過實現(xiàn)SequenceType協(xié)議。SequenceType協(xié)議有一個Generator實現(xiàn)GeneratorType協(xié)議,并通過Generator的next方法來取值,這樣就可以通過連續(xù)取值,來實現(xiàn)for循環(huán)遍歷了。同時通過實現(xiàn)ArrayLiteralConvertible協(xié)議和subscript,就可以通過字面量來創(chuàng)建數(shù)組,并通過下標來取值。
CollectionType
上面我們?yōu)榱伺宄equenceType的實現(xiàn)原理,通過實現(xiàn)SequenceType和GeneratorType來實現(xiàn)數(shù)組,但實際上Swift系統(tǒng)的Array類型是通過實現(xiàn)CollectionType來獲得這些特性的,而CollectionType協(xié)議又遵守Indexable和SequenceType這兩個協(xié)議。并擴展了兩個關聯(lián)類型Generator和SubSequence,以及9個方法,但這兩個關聯(lián)類型都是默認值,而且9個方法也都在協(xié)議擴展中有默認實現(xiàn)。因此,我們只需要為Indexable協(xié)議中要求的 startIndex 和 endIndex 提供實現(xiàn),并且實現(xiàn)一個通過下標索引來獲取對應索引的元素的方法。只要我們實現(xiàn)了這三個需求,我們就能讓一個類型遵守 CollectionType 了。因此這個自定義的數(shù)組可以這樣實現(xiàn):
struct MYArray<Element>: CollectionType {
private var dic: [Int: Element]
init(elements: Element...) {
dic = [Int: Element]()
elements.forEach { dic[dic.count] = $0 }
}
var startIndex: Int { return 0 }
var endIndex: Int { return dic.count }
subscript(idx: Int) -> Element {
precondition(idx < endIndex, "Index out of bounds")
return dic[idx]!
}
}
extension MYArray: ArrayLiteralConvertible {
init(arrayLiteral elements: Element...) {
dic = [Int: Element]()
elements.forEach { dic[dic.count] = $0 }
}
}



查看完整回答
反對 回復 2019-03-22
  • 2 回答
  • 0 關注
  • 896 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號