map(keyPath) where keyPath is a variable - swift

let arr = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)]
arr.map(\.0) // [1, 2, 3, 4, 5]
Works great. But the below code doesn't compile:
let keyPath = \(Int, Int).0
arr.map(keyPath)
Cannot convert value of type 'WritableKeyPath<(Int, Int), Int>' to
expected argument type '((Int, Int)) throws -> T'.
Generic parameter 'T' could not be inferred.

Array.map expects a closure with signature (Element) throws -> T.
In Swift 5.2, key paths were allowed to be passed in as functions/closures (here's an evolution proposal), but only as literals (at least, according to the proposal, it says "for now", so perhaps this restriction would be lifted).
To overcome this, you can create an extension on Sequence that accepts a key path:
extension Sequence {
func map<T>(_ keyPath: KeyPath<Element, T>) -> [T] {
return map { $0[keyPath: keyPath] }
}
}
(credit to: https://www.swiftbysundell.com/articles/the-power-of-key-paths-in-swift/)
Then you can do what you wanted:
let keyPath = \(Int, Int).0
arr.map(keyPath)

The evolution proposal showed how to do it with an operator, but you can also use the same [] or () syntax whether it's partially-applied or not, because subscripts and functions don't need arguments.
let oneTo5 = 1...5
let keyPath = \(Int, Int).0
XCTAssert(
zip(oneTo5, oneTo5).map(keyPath[]).elementsEqual(oneTo5)
)
let keyPath = \Double.isZero
XCTAssertFalse(keyPath[1.0]())
public extension KeyPath {
/// Convert a `KeyPath` to a partially-applied get accessor.
subscript() -> (Root) -> Value {
{ $0[keyPath: self] }
}
/// Convert a `KeyPath` to a get accessor.
subscript(root: Root) -> () -> Value {
{ root[keyPath: self] }
}
}
public extension ReferenceWritableKeyPath {
/// Convert a `KeyPath` to a partially-applied get/set accessor pair.
subscript() -> (Root) -> Computed<Value> {
{ self[$0] }
}
/// Convert a `KeyPath` to a get/set accessor pair.
subscript(root: Root) -> Computed<Value> {
.init(
get: self[root],
set: { root[keyPath: self] = $0 }
)
}
}
/// A workaround for limitations of Swift's computed properties.
///
/// Limitations of Swift's computed property accessors:
/// 1. They are not mutable.
/// 2. They cannot be referenced as closures.
#propertyWrapper public struct Computed<Value> {
public typealias Get = () -> Value
public typealias Set = (Value) -> Void
public init(
get: #escaping Get,
set: #escaping Set
) {
self.get = get
self.set = set
}
public var get: Get
public var set: Set
public var wrappedValue: Value {
get { get() }
set { set(newValue) }
}
public var projectedValue: Self {
get { self }
set { self = newValue }
}
}
//MARK:- public
public extension Computed {
init(
wrappedValue: Value,
get: #escaping Get = {
fatalError("`get` must be assigned before accessing `wrappedValue`.")
},
set: #escaping Set
) {
self.init(get: get, set: set)
self.wrappedValue = wrappedValue
}
}

Related

Typescript Generic chained function to Swift

I'm really struggling to comprehend how to (if even possible) to convert a generics function written in Typescript into something I can use in Swift.
export type Filter<T> = (value: T) => boolean
export function isKeyEqualToValue<T>(key: keyof T) {
return function (value: T[keyof T]): Filter<T> {
return (object: T) => object[key] === value
}
}
isKeyEqualToValue<T>('key')(someObject.key)
const filters = userFilters.map(userFilterSet => isEvery(buildAlertFilter(userFilterSet)))
const isMatch = isAny(filters)
return flow.reduce((feed: String[], obj: SomeType) => {
if (!isMatch(obj)) return feed
return [
...feed,
{
...obj
},
]
}, [])
}
I would like to be able to input a struct model in for T and check if the inputted value matches the key. Would greatly appreciate some guidance here!
EDIT:
I've added how the method is being called and used. Essentially I'm trying to avoid doing an algorithm O(n)^2 and so I'm trying to build a list of filters based on our user's choice. Then cross check the bulk of my data (SomeType) with those built filters.
I'm working to translate another function using the similar principles.
export function hasInArray<T>(key: keyof T) {
return function (values: Array<any>): Filter<T> {
return (object: T) => values.includes((object[key] as unknown) as string)
}
}
This is what I have so far.
func notInArray<Root, Value>(for keyPath: KeyPath<Root, Value>) -> (Array<Any>) -> Filter<Root, Value> {
{ values in { object in !values.contains(where: object[keyPath: keyPath]) } } }
You haven't given how you expect to use this, so I need to make some assumptions. I'm assuming the TypeScript that calls this looks like this:
interface Person {
name: string;
age: number;
}
const key: keyof Person = "name";
const nameTester = isKeyEqualToValue(key);
const person = {name: "Alice", age: 23};
const result = nameTester("Alice")(person);
The equivalent to TypeScript's keyof in Swift is KeyPath. Keeping this as close to the TypeScript syntax as possible to make it easier to see how it maps, this would look like:
typealias Filter<T> = (_ value: T) -> Bool
func isKeyEqualToValue<T, Value>(key: KeyPath<T, Value>) -> (Value) -> (T) -> Bool
where Value: Equatable
{
return { (value: Value) -> Filter<T> in
return { (object: T) in object[keyPath: key] == value }
}
}
struct Person: Equatable {
var name: String
var age: Int
}
let key = \Person.name
let nameTester = isKeyEqualToValue(key: key)
let person = Person(name: "Alice", age: 23)
let result = nameTester("Alice")(person)
To make it better Swift (rather than matching the TypeScript so closely), it would look like:
typealias Filter<Root, Value: Equatable> = (Value) -> (Root) -> Bool
func isEqualToValue<Root, Value>(for keyPath: KeyPath<Root, Value>) -> Filter<Root, Value>
{
{ value in { object in object[keyPath: keyPath] == value } }
}
let nameTester = isEqualToValue(for: key)
Your second example is like the first.
func hasInArray<Root, Values>(for keyPath: KeyPath<Root, Values>) -> (Values.Element) -> (Root) -> Bool
where Values: Sequence, Values.Element: Equatable
{
{ value in { object in object[keyPath: keyPath].contains(value) } }
}
You will almost never want Array<Any>. You need an array of the specific element. But in this case you don't need an array at all; you just need any Sequence.
All this said, I wouldn't do it this way. I think it's much easier to understand if you create a Filter type to manage it.
// A Filter object over a specific Target object (for example, a Person)
struct Filter<Target> {
let passes: (Target) -> Bool
}
// Filters can be created many ways
extension Filter {
// By properties equal to a value
static func keyPath<Value>(_ keyPath: KeyPath<Target, Value>, equals value: Value) -> Filter
where Value: Equatable
{
Filter { target in
target[keyPath: keyPath] == value
}
}
// By properties containing a value
static func keyPath<Seq>(_ keyPath: KeyPath<Target, Seq>, contains value: Seq.Element) -> Filter
where Seq: Sequence, Seq.Element: Equatable
{
Filter { target in
target[keyPath: keyPath].contains(value)
}
}
// By a property being a member of a sequence
static func keyPath<Seq>(_ keyPath: KeyPath<Target, Seq.Element>, isElementOf seq: Seq) -> Filter
where Seq: Sequence, Seq.Element: Equatable
{
Filter { target in
seq.contains(target[keyPath: keyPath])
}
}
// By combining other filters
static func all(of filters: [Filter]) -> Filter {
Filter { target in
filters.allSatisfy { filter in filter.passes(target) }
}
}
}
struct Person {
var name: String
var age: Int
var children: [String]
}
let filter: Filter<Person> = .all(of: [
.keyPath(\.name, equals: "Alice"),
.keyPath(\.children, contains: "Bob"),
.keyPath(\.age, isElementOf: [23, 43]),
])
let alice = Person(name: "Alice", age: 23, children: ["Bob"])
let shouldInclude = filter.passes(alice) // true

how to store away sequence variables with constraints in swift

I wanted to create a "where_non_null" operation that works on any swift sequence - which is easy if you return an array, but obviously that is potentially bad performance wise - because you are forcing the entire sequence to resolve in memory - so I created the following that just goes line by line:
//
// this iterates through the underlying sequence, and returns only the values that are not null
//
public class Not_null_iterator<T> : IteratorProtocol
{
public typealias Element = T
private let next_function : () -> T?
init<T_iterator: IteratorProtocol>( _ source: T_iterator ) where T_iterator.Element == Optional<T>
{
var iterator = source
next_function =
{
while (true)
{
if let next_value = iterator.next()
{
if let not_null_value = next_value
{
return not_null_value
}
}
else
{
return nil
}
}
}
}
public func next() -> T? {
next_function()
}
}
//
// a sequence wrapping an underlying sequence, that removes any nulls as we go through
//
public class Not_null_sequence<T > : Sequence
{
private var iterator_creator : () -> Not_null_iterator<T>
init<T_source_sequence : Sequence >( _ source : T_source_sequence ) where T_source_sequence.Element == Optional<T>
{
iterator_creator =
{
Not_null_iterator(source.makeIterator())
}
}
public func makeIterator() -> Not_null_iterator<T>
{
iterator_creator()
}
}
extension Sequence
{
//
// return only the not null values in the sequence without ever resolving more than one item in memory at one time and remove the optionality on the type
//
func where_not_null<T>() -> Not_null_sequence<T> where Element == Optional<T>
{
return Not_null_sequence( self)
}
}
class Where_not_null_tests : XCTestCase
{
public func test_where_not_null()
{
let source = [1, 2, 3, nil, 4]
let checked : [Int] = Array(source.where_not_null())
XCTAssertEqual([1,2,3,4],checked)
}
}
which works great - however I had to define the next() and make_iterator() functions in the constructor, because I couldn't find any type safe way of putting the source into a class level variable.
Is there a way of doing that?
[and yes, I'm aware swift people prefer camel case]
Rather than just using one generic parameter, you'd need two generic parameters. You can't just constrain one generic parameter to say that it has to be some sequence with an element of some Optional. You need another generic parameter to say what the optional's type is:
class NotNilIterator<T: IteratorProtocol, U>: IteratorProtocol where T.Element == U? {
typealias Element = U
var iterator: T
init(_ source: T) {
iterator = source
}
func next() -> Element? {
// I feel this is clearer what is going on
while true {
switch iterator.next() {
case .some(.none):
continue
case .none:
return nil
case .some(.some(let element)):
return element
}
}
}
}
class NotNilSequence<T: Sequence, U> : Sequence where T.Element == U?
{
let sequence: T
init(_ source : T)
{
sequence = source
}
public func makeIterator() -> NotNilIterator<T.Iterator, U>
{
.init(sequence.makeIterator())
}
}
whereNotNil would then be declared like this:
func whereNotNil<T>() -> NotNilSequence<Self, T> where Self.Element == T?
{
return .init(self)
}
Note the use of self types. The first parameter is the type of the underlying sequence, the second is the non-optional type.
Note that this sort of "lazily computed sequence" is already built into Swift. To lazily filter out the nils, do:
let array = [1, 2, 3, nil, 4]
let arrayWithoutNil = array.lazy.compactMap { $0 }
The downside is that the type names are quite long. arrayWithoutNil is of type
LazyMapSequence<LazyFilterSequence<LazyMapSequence<LazySequence<[Int?]>.Elements, Int?>>, Int>
But you can indeed get non-optional Ints out of it, so it does work.
The way swift generics work can sometimes be very confusing (but has it's advantages). Instead of declaring that a variable is of a generic protocol (resp. a protocol with associated types), you instead declare another generic type which itself conforms to your protocol. Here's your iterator as an example (I have taken the liberty to clean up the code a bit):
public class Not_null_iterator<T, T_iterator> : IteratorProtocol where
T_iterator: IteratorProtocol,
T_iterator.Element == Optional<T>
{
private var source: T_iterator
init(_ source: T_iterator) {
self.source = source
}
public func next() -> T? {
while let next_value = source.next()
{
if let not_null_value = next_value
{
return not_null_value
}
}
return nil
}
}
The non-null sequence works analogous:
public class Not_null_sequence<T, Source>: Sequence where
Source: Sequence,
Source.Element == Optional<T>
{
private var source: Source
init(_ source: Source) {
self.source = source
}
public func makeIterator() -> Not_null_iterator<T, Source.Iterator> {
Not_null_iterator(self.source.makeIterator())
}
}
Using this some IteratorProtocol is just a nice way to let the compiler figure out the type. It is equivalent to saying Not_null_iterator<T, Source.Iterator>
As a (potentially) interesting side-note, to clean up the generic mess even more, you can nest the iterator class inside the Not_null_sequence:
public class Not_null_sequence<T, Source>: Sequence where
Source: Sequence,
Source.Element == Optional<T>
{
private var source: Source
init(_ source: Source) {
self.source = source
}
public func makeIterator() -> Iterator{
Iterator(self.source.makeIterator())
}
public class Iterator: IteratorProtocol {
private var source: Source.Iterator
init(_ source: Source.Iterator) {
self.source = source
}
public func next() -> T? {
while let next_value = source.next()
{
if let not_null_value = next_value
{
return not_null_value
}
}
return nil
}
}
}

Obscure low-level fatal error in Swift

I have a Swift implementation of an Ordered Set that I believe is correct (if not very efficient), since NSOrderedSet won't work with non-ObjC structures. However, when using the class in a multi-threaded app, I occasionally get a very low level crash which reports nothing on the console but "fatal error", and shows this in the debugger:
function signature specialization <preserving fragile attribute, Arg[1] =
[Closure Propagated : reabstraction thunk helper from #callee_owned
(#unowned Swift.UnsafeBufferPointer<Swift.UInt8>) -> () to
#callee_owned (#unowned Swift.UnsafeBufferPointer<Swift.UInt8>) ->
(#out ()), Argument Types : [#callee_owned (#unowned
Swift.UnsafeBufferPointer<Swift.UInt8>) -> ()]> of generic
specialization <preserving fragile attribute, ()> of
Swift.StaticString.withUTF8Buffer <A>
((Swift.UnsafeBufferPointer<Swift.UInt8>) -> A) -> A
The code being executed is this:
import Foundation
fileprivate struct OrderedSetElementWrapper<T>: Hashable, Equatable where T: Hashable, T: Equatable {
let value: T
let index: Int
var hashValue: Int { return self.value.hashValue }
}
fileprivate func ==<T>(lhs: OrderedSetElementWrapper<T>, rhs: OrderedSetElementWrapper<T>) -> Bool {
return lhs.value == rhs.value
}
public struct OrderedSet<T> where T: Hashable, T: Equatable {
private var _set = Set<OrderedSetElementWrapper<T>>()
init() {}
init(array: [T]) { array.forEach { self.insert($0) } }
var array: [T] {
// ***** Error intermittently on next line ******
let sortedArray = self._set.sorted { $0.index < $1.index }
// **********************************************
let mapped = sortedArray.map { $0.value }
return mapped
//return self._set.sorted(by: { $0.index < $1.index }).map({ $0.value })
}
var set: Set<T> { return Set(self._set.map { $0.value } ) }
var count: Int { return self._set.count }
func contains(item: T) -> Bool { return self.set.contains(item) }
mutating func insert(_ item: T) {
self._set.insert(OrderedSetElementWrapper(value: item, index: self._set.count))
}
mutating func remove(_ item: T) {
var newSet = Set<OrderedSetElementWrapper<T>>()
for element in self._set {
if element.value != item {
newSet.insert(OrderedSetElementWrapper(value: element.value, index: newSet.count))
}
}
self._set = newSet
}
}
The class works perfectly the vast majority of the time, I'm reasonably sure of the logic, and I simply don't understand the error message! Can anyone explain the error message?
The error is triggered by a call to the .array property. The calling class is
public class XXXItemGroupBase: XXXItemBase {
// ***************************************
// MARK: New properties
// ***************************************
private var _theItems = OrderedSet<XXXItemBase>()
// _theItems is used as a private backing store.
// Do NOT access it directly outside of the class -
// use self.components instead...
// ***************************************
// MARK: Overridden properties
// ***************************************
override public var components: [XXXItemBase] { // The public face of self._theItems
get { return self._theItems.array } // **** CRASH HERE ****
set { self._theItems = OrderedSet(array: newValue) }
}

Swift subscript with different signature for the getter and setter

Is it possible to have a subscript in Swift that has different signatures for the getter and setter?
For example, I want the getter to return a Set<Int> and the setter to take an Int (not a Set<Int>).
This code won't compile but it gives you an idea of what I'm trying to do:
struct Foo{
subscript(index: Int)->String{
get{
return "bar" // returns a String
}
set(newValue: String?){ // takes a String? instead of a String
print(newValue)
}
}
}
How can I do this?
This is very ugly, and I strongly discourage you from doing so, but technically this is possible:
struct Foo {
subscript(concreteValueFor index: Int) -> String {
return "Get concrete \(index)"
}
subscript(optionalValueFor index: Int) -> String? {
get { return nil }
set { print("Set optional \(index)") }
}
}
var foo = Foo()
foo[concreteValueFor: 1] // Returns "Get concrete 1"
foo[optionalValueFor: 2] = "" // Prints "Set optional 2"
For a multimap some time ago I made something like this:
public struct Multimap<Key: Hashable, Value: Hashable>: CollectionType {
public typealias _Element = Set<Value>
public typealias Element = (Key, _Element)
public typealias Index = DictionaryIndex<Key, _Element>
public typealias Generator = DictionaryGenerator<Key, _Element>
private typealias Storage = [Key: _Element]
private var storage = Storage()
public var startIndex: Index { return storage.startIndex }
public var endIndex: Index { return storage.endIndex }
public subscript(position: Index) -> _Element { return storage[position].1 }
public subscript(position: Index) -> Element { return storage[position] }
subscript(key: Key) -> Set<Value> {
get { return storage[key] ?? Set<Value>() }
set { storage[key] = newValue.isEmpty ? nil : newValue }
}
public func generate() -> Generator { return storage.generate() }
}
Usage:
var foo = Multimap<Int, String>()
foo[0] // Returns an emtpy Set<String>
foo[0].insert("Ook") // Inserts a value at index 0
foo[0].insert("Eek")
foo[0] // Now this returns a set { "Ook", "Eek" }
foo[1].insert("Banana")
foo[1].insert("Book")
foo[0].unionInPlace(foo[1])
foo[0] // Returns a set { "Banana", "Ook", "Eek", "Book" }

How can I write a function that will unwrap a generic property in swift assuming it is an optional type?

So far I have only been able to achieve this using a global function. I am not sure if it is possible but I was hoping to write an extension to a generic class that would hopefully achieve the same thing.
Below is the working global function it is using SignalProducer class from ReactiveCocoa but the principle should be the same for any generic class.
func ignoreNilValues <Value,Error> (producer: SignalProducer<Value?,Error>) -> SignalProducer<Value, Error> {
return producer.filter { return $0 != nil }.map { $0! }
}
Update:
I have made progress but have still fallen short of a complete solution
Given any class with some generic property
class GenericClass<SomeType> {
var someProperty: [SomeType] = []
}
How can I write an extension that will filter any optional values and return the value using the Wrapped type?
The following will filter any nil values but still return it as the Optional type.
protocol AnOptional {
var isNil: Bool {get}
}
extension Optional : AnOptional {
var isNil: Bool {
get {
guard let hasValue = self.map({ (value: Wrapped) -> Bool in
return true
}) else {
return true
}
return !hasValue
}
}
}
extension GenericClass where SomeType : AnOptional {
func filterNilValuesOfSomeProperty() -> [SomeType] {
return someProperty.filter({ (anOptional: AnOptional) -> Bool in
return !anOptional.isNil
})
}
}
As can be seen
let aClass = GenericClass<Int?>()
aClass.someProperty = [3,5,6,nil,4,3,6, nil]
let x = aClass.someProperty
//x = [Some(3),Some(5),Some(6),nil,Some(4),Some(3),Some(6), nil]
let y = aClass.filterNilValuesOfSomeProperty()
//y = [Some(3),Some(5),Some(6),Some(4),Some(3),Some(6)]
Is it possible to write a class extension that would return the wrapped type? In the example above it would be [Int] instead of [Int?].
I rewrote the global function solution for this example.
func ignoreNilValues <Value> (aClass: GenericClass<Value?>) -> GenericClass<Value> {
let aNewClass = GenericClass<Value>()
aNewClass.someProperty = aClass.someProperty.filter({ (v: Value?) -> Bool in
v != nil
}).map { (oldValue: Value?) -> Value in
return oldValue!
}
return aNewClass
}
let z = ignoreNilValues(aClass).someProperty
//z = [3, 5, 6, 4, 3, 6]
The "trick" is to define a protocol to which all optionals conform
(this is from Creating an extension to filter nils from an Array in Swift
with a minor simplification; the idea goes back to this Apple Forum Thread):
protocol OptionalType {
typealias Wrapped
func intoOptional() -> Wrapped?
}
extension Optional : OptionalType {
func intoOptional() -> Wrapped? {
return self
}
}
You can use that in your case as:
class GenericClass<SomeType> {
var someProperty: [SomeType] = []
}
extension GenericClass where SomeType : OptionalType {
func filterNilValuesOfSomeProperty() -> [SomeType.Wrapped] {
return someProperty.flatMap { $0.intoOptional() }
}
}
which uses the flatMap() method from SequenceType:
extension SequenceType {
/// Return an `Array` containing the non-nil results of mapping
/// `transform` over `self`.
///
/// - Complexity: O(*M* + *N*), where *M* is the length of `self`
/// and *N* is the length of the result.
#warn_unused_result
public func flatMap<T>(#noescape transform: (Self.Generator.Element) throws -> T?) rethrows -> [T]
}
Example:
let aClass = GenericClass<Int?>()
aClass.someProperty = [3,5,6,nil,4,3,6, nil]
let x = aClass.someProperty
print(x) // [Optional(3), Optional(5), Optional(6), nil, Optional(4), Optional(3), Optional(6), nil]
let y = aClass.filterNilValuesOfSomeProperty()
print(y) // [3, 5, 6, 4, 3, 6]
In Swift 3 and later the protocol has to be defined as
protocol OptionalType {
associatedtype Wrapped
func intoOptional() -> Wrapped?
}
I have this solution using in my app, create a protocol, and added an extension to Optional.
protocol OptionalUnwrap {
associatedtype Wrapped
func unwrap(default defaultValue: #autoclosure () -> Wrapped) -> Wrapped
}
extension Optional: OptionalUnwrap {
func unwrap(default defaultValue: #autoclosure () -> Wrapped) -> Wrapped {
if let value = self {
return value
}
return defaultValue()
}
}
You can use it like this, you have to provide a default value, so if optional is nil it will return the default value. It works with all types.
struct StructName {
var name: String
var age: Int
}
var structName3: StructName?
let unwrapped = structName3.unwrap(default: StructName(name: "", age: 2345))
print(unwrapped.age)
var version: Int?
version.unwrap(default: 5)
var subject: String? = "iOS"
subject.unwrap(default: "")