ios - Swift 中的某些东西类似于 C# 中的 LINQ

标签 ios linq swift dsl

我知道 Swift 还比较新,但我想知道 Swift 是否有类似 LINQ 的东西在 C# 中?

对于 LINQ,我指的是所有出色的工具,例如标准查询运算符Anonymous types , 对象初始化器

最佳答案

Swift 合并了一些在 .net 中作为 LINQ 捆绑在一起的功能,尽管可能不是开箱即用的感觉。

匿名类型非常类似于 Swift 中具有命名值的元组。

在 C# 中:

   var person = new { firstName = "John", lastName = "Smith" };
   Console.WriteLine(person.lastName);

Output: Smith

在 Swift 中:

var person = (firstName: "John", lastName: "Smith")
person.firstName = "Fred"
print(person.lastName)

Output: Smith

LINQ 查询当然非常强大/富有表现力,但您可以使用 mapfilterreduce 在 swift 。使用 lazy,您可以获得与创建可提前循环的对象相同的功能,并且仅在循环实际发生时才对其求值:

在 C# 中:

var results =
 SomeCollection
    .Where(c => c.SomeProperty < 10)
    .Select(c => new {c.SomeProperty, c.OtherProperty});

foreach (var result in results)
{
    Console.WriteLine(result.ToString());
}

在 Swift 中:

// just so you can try this out in a playground...
let someCollection = [(someProperty: 8, otherProperty: "hello", thirdProperty: "foo")]

let results =
  someCollection.lazy
    .filter { c in c.someProperty < 10 }
    // or instead of "c in", you can use $0:
    .map { ($0.someProperty, $0.otherProperty) }

for result in results {
    print(result)
}

Swift 泛型使类似于现有 LINQ 功能的编写操作变得非常简单。例如,来自 LINQ wikipedia article :

Count The Count operator counts the number of elements in the given collection. An overload taking a predicate, counts the number of elements matching the predicate.

可以像这样用 Swift 编写(2.0 协议(protocol)扩展语法):

extension SequenceType {
    // overload for count that takes a predicate
    func count(match: Generator.Element -> Bool) -> Int {
        return reduce(0) { n, elem in match(elem) ? n + 1 : n }
    }
}

// example usage
let isEven = { $0 % 2 == 0 }

[1,1,2,4].count(isEven)  // returns 2

如果元素符合 Equatable,您也可以重载它以获取特定元素来计数:

extension SequenceType where Generator.Element: Equatable {
    // overload for count that takes a predicate
    func count(element: Generator.Element) -> Int {
        return count { $0 == element }
    }
}

[1,1,2,4].count(1)

默认情况下,结构具有类似对象初始化程序的语法:

struct Person { let name: String; let age: Int; }

let person = Person(name: "Fred Bloggs", age: 37)

并且通过ArrayLiteralConvertible,任何集合类型都可以具有与集合初始化语法相似的语法:

let list: MyListImplementation = [1,2,3,4]

关于ios - Swift 中的某些东西类似于 C# 中的 LINQ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655304/

相关文章:

ios - 在 UICollectionView swift 中获取单元格 onClick 的所有 subview

.net - 在 LINQ 中与匿名类型不同(在 VB.NET 中)

linq - SharePoint、List.Items 和 List.GetItems(Query) 和 Linq

arrays - Swift 根据总值(value)将数组分割成 block

ios - 使用 CocoaPods 作为 "Charts"框架。 swift 2

ios - 想要在我的应用程序中访问 iPhone 常规设置内容

ios - 如何更改 Xcode 6 中对象的堆叠顺序?

ios - 使用 SwiftUI 在不同的 UI 层次结构之间切换的正确方法是什么?

c# - 如何将此 linqTOsql 查询转换为 lambda

ios - 为什么通过 UITabBarController.viewDidLoad 中的代码添加的自定义按钮不响应选择器