[英]Array filter in Swift3
我有一段代碼。 我不知道這段代碼里面有什么內容。 任何人都可以解釋一下嗎?
let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]
let res = wordFreqs.filter(
{
(e) -> Bool in
if e.1 > 3 {
return true
} else {
return false
}
}).map { $0.0 }
print(res)
給出輸出:
["k","a"]
如果我們一個接一個地使用這段代碼:
let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]
你從一系列元組開始 。
從Swift文檔:
元組類型是以逗號分隔的類型列表,括在括號中。
和:
元組將多個值分組為單個復合值。 元組中的值可以是任何類型。
在這種情況下,元組是2個值的“耦合”,一個是String類型,另一個是Int類型。
let res = wordFreqs.filter(
{
(e) -> Bool in
這部分在數組上應用了一個過濾器。 你可以在這里看到過濾器的閉包需要一個元素e(所以,在我們的例子中,是一個元組),然后返回一個Bool。 使用'filter'函數,返回true表示保留值,而返回false表示將其過濾掉。
if e.1 > 3 {
return true
} else {
return false
}
e.1
語法返回索引1處元組的值。因此,如果索引1(第二個)的元組值超過3,則過濾器返回true(因此將保留元組); 如果不是,則過濾器返回false(因此從結果中排除元組)。 此時,過濾器的結果將是[("k", 5), ("a", 7)]
}).map { $0.0 }
map函數基於元組數組創建一個新數組:對於輸入數組的每個元素($ 0),它返回索引0處的元組值。所以新數組是["k", "a"]
print(res)
這會將結果打印到控制台。
這些函數(濾波器,映射,縮減等)在函數式編程中非常常見。 它們通常使用點語法鏈接,例如, [1, 2, 3].filter({ }).map({ }).reduce({ })
// this creates an array of tuples
let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]
let res = wordFreqs.filter {
(e) -> Bool in
// this filters the array
// it removes any items that have the second part of the tuple
// of 3 or less
if e.1 > 3 {
return true
} else {
return false
}
}.map {
// this "maps" the array and returns the first part of the tuple
$0.0
}
print(res)
注意......如果我寫這篇文章,我會把它縮短為......
let res = wordFreqs.filter { $0.1 > 3 }
.map { $0.0 }
wordFreqs
是tuple
數組。
元組
元組是表示為一個值的零個或多個值的組。
例如 (“John”,“Smith”)擁有一個人的名字和姓氏。 您可以使用點(。)表示法后跟值的索引來訪問內部值:
var person = ("John", "Smith")
var firstName = person.0 // John
var lastName = person.1 // Smith
現在在你的情況下你有一個類型(String, Int)
元組和你正在比較e.1 > 3
filter
(這里e
是保持帶有filter
的數組迭代的元組值)意味着second(Int)
值更大比3。
之后,您在filter
結果上使用map
,並從元組重新調整String($0.0)
。
//array of tuples
let wordFreqs = [("k", 5), ("a", 7), ("b", 3)]
let res = wordFreqs.filter(
{
(e) -> Bool in
//Comparing the Second Int value of tuple in filter
if e.1 > 3 {
return true
} else {
return false
}
})
//Mapping the result of filter
.map {
//return the String from the tuple
$0.0
}
您的e
對象表示(String, int)
類型。 正如你在[("k", 5), ("a", 7), ("b", 3)]
中的數組中看到的那樣。
首先,您使用的是filter
方法,這就是您必須返回true
或false
值的原因。 在這種情況下,您檢查e.1
(表示int值)是否大於3,否則返回false。 在所有這個過程之后, filter
方法返回(String,int)對象的過濾數組。
下一步是map
功能。 在你的情況下很簡單,它只是將所有數組值映射到元組的第一個對象(String,int)。
為了更好地理解您的代碼可能如下所示:
let filteredArray = wordFreqs.filter
({
(e) -> Bool in
return e.1 > 3
})// the filteredArray is [("k", 5), ("a", 7)]
let finalValue = filteredArray.map {
$0.0
}// here you're creating a new array with String. $0 represents object from filteredArray
print(finalValue) // ["k", "a"]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.