How to pass a "Sequence" of type "T" as a parameter in Swift? - ios

Suppose I have a function that takes a sequence of "Person" objects. The sequence could be a simple array, or RealmSwift's Result, or List:
// A simple array
func someFunction(people: [Person]) {
}
// Result
func someFunction(people: Result<Person>) {
}
// List
func someFunction(people: List<Person>) {
}
Instead of having these 3 functions, I want to have only 1 function that takes a generic sequence of "Person" objects, something that looks like this:
func someFunction(people: Sequence<Person>) {
}
This way, I could pass an array, a Result or a List to the function and not have to worry that the types don't match. But obviously this is not allowed in Swift. How do I do that then?

EDIT: Xcode 14.1 and Swift 5.7.1 were released today, and with these versions, you can now do this just with:
func someFunction(people: some Sequence<Person>) { ... }
Original answer is below.
--
You can do this with a where clause. Read about where clauses here:
https://docs.swift.org/swift-book/LanguageGuide/Generics.html#ID192
To answer your specific question, you can create a generic Sequence constraint and constrain its Element like so:
func someFunction<S: Sequence>(people: S) where S.Element == Person { ... }

Related

Set (Collection) - Insert multiple elements

Set is an unordered collection of unique elements. Almost similar to array.
I want to add/insert multiple elements in a Set of String. But there is only single method provided that can insert only one element (accepts single Set element as a parameter argument) and I've collection of string (id).
insert(_:)
#discardableResult mutating func insert(_ newMember: Set.Element) -> (inserted: Bool, memberAfterInsert: Set.Element)
How can I do that?
What I've tried:
I tried to create an extension very similar to insert(_:) method but it can accept multiple Set elements. It would be same as use of iteration over collection but don't need to handle it manually everywhere.
extension Set {
#discardableResult mutating func insert(_ newMembers: [Set.Element]) -> (inserted: Bool, memberAfterInsert: Set.Element) {
newMembers.forEach { (member) in
self.insert(member)
}
}
}
It should work, if I return a tuple as expected but no idea how and where (which line) and what to return a value.
Here is error message.
Missing return in a function expected to return '(inserted: Bool, memberAfterInsert: Set.Element)'
What can be solution to this. Is there any better solution/approach to handle this operation?
It was pointed out in the comments under the question, but I'd like to clearly state that there is a method for that very same purpose:
mutating func formUnion<S>(_ other: S) where Element == S.Element, S : Sequence
Usage:
var attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Diana", "Marcia", "Nathaniel"]
attendees.formUnion(visitors)
print(attendees)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
Source: Apple Developer
There is also an immutable variant which returns a new instance containing the union:
func union<S>(_ other: S) -> Set<Set.Element> where Element == S.Element, S : Sequence
Usage:
let attendees: Set = ["Alicia", "Bethany", "Diana"]
let visitors = ["Marcia", "Nathaniel"]
let attendeesAndVisitors = attendees.union(visitors)
print(attendeesAndVisitors)
// Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
Source: Apple Developer
Swift Set Union
[Swift Set operations]
a.union(b) - a ∪ b - the result set contains all elements from a and b
union - immutable function
unionInPlace(up to Swift 3) => formUnion - mutable function
[Mutable vs Immutable]
Read more here
Your insert declaration states that the method is returning a tuple: (inserted: Bool, memberAfterInsert: Set.Element), but your method does not return anything.
Just use:
#discardableResult mutating func insert(_ newMembers: [Set.Element]) {
newMembers.forEach { (member) in
self.insert(member)
}
}
UPDATE
The closest to get is this I believe:
extension Set {
#discardableResult mutating func insert(_ newMembers: [Set.Element]) -> [(inserted: Bool, memberAfterInsert: Set.Element)] {
var returnArray: [(inserted: Bool, memberAfterInsert: Set.Element)] = []
newMembers.forEach { (member) in
returnArray.append(self.insert(member))
}
return returnArray
}
}
Reasoning:
The docs to the insert say:
Return Value
(true, newMember) if newMember was not contained in the set. If an element equal to newMember was already contained in the set, the method returns (false, oldMember), where oldMember is the element that was equal to newMember. In some cases, oldMember may be distinguishable from newMember by identity comparison or some other means.
E.g., for set {1, 2, 3} if you try to insert 2, the tuple will return (false, 2), because 2 was already there. The second item of the tuple would be object from the set and not the one you provided - here with Ints it's indistinguishable, since only number 2 is equal to 2, but depending on Equatable implementation you can have two different objects that would be evaluated as the same. In that case the second argument might be important for us.
Anyway, what I am trying to say is, that a single tuple therefore corresponds to a single newMember that you try to insert. If you try to insert multiple new members, you cannot describe that insertion just by using a single tuple - some of those new members might have already been there, thus for the the first argument would be false, some other members might be successfully inserted, thus for them the first argument of tuple would be true.
Therefore I believe the correct way is to return an array of tuples [(inserted: Bool, memberAfterInsert: Set.Element)].
I think what you are looking for is this:
extension Set {
mutating func insert(_ elements: Element...) {
insert(elements)
}
mutating func insert(_ elements: [Element]) {
for element in elements {
insert(element)
}
}
}
The example in your question is breaking a couple of good software programming principals, such as the single responsibility rule. It seems like your function is trying to both modify the current set and return a new set. Thats really confusing. Why would you ever want to do that?
If you are trying to create a new set from multiple sets, then you can do the following:
extension Set {
/// Initializes a set from multiple sets.
/// - Parameter sets: An array of sets.
init(_ sets: Self...) {
self = []
for set in sets {
for element in set {
insert(element)
}
}
}
}

Closures In Swift?

I am new to iOS coding and I am stuck in closures feature of SWIFT. I have referred to many tutorials and found that closures are self written codes which can be used in many ways eg. as arguments in function call,parameters in function definition,variables. I am giving below an example below with my associated thoughts about the code & questions. Please help me if I am wrong in my understanding. I know I am wrong at many points,so please rectify me.
1.1st Part
func TEST(text1:String,text2:String,flag: (S1:String,S2:String)->Bool)//In this line,I think,I am using flag is a closure which is passed as parameter in a function. And if so why doesn't it follow the standard closure syntax?
{
if flag(S1: text1, S2: text2) == true//I want to check the return type what flag closure gets when it compares the both string during function call. Why can't I write as if flag == true as flag is the name of the closure and ultimately refers to the return type of the closure?
{
print("they are equal")
}
else
{
//
}
}
2nd Part
This part is the most troublesome part that really confuses me when I am calling the function. Here I am also using the same closure. What is happening over here? How is the closure being used? Is it capturing values or something else?
TEST("heyy", text2: "heyy") { (S1, S2) -> Bool in
S1==S2
}
Thanks for your kind consideration.
Your closure usage is ok. A closure is some code that can be passed to be executed somewhere else. In your case you can choose to pass the real test you want to the function TEST, simple string test or case-insensitive test, etc. This is one of the first usage of closure: obtain more genericity.
And yes closures capture something, it captures some part of the environnement, i.e. the context in which they are defined. Look:
var m = "foo"
func test(text1:String, text2:String, testtFunc: (s1:String, s2:String) -> Bool) {
m = "bar"
if testFunc(s1: text1, s2: text2) { print("the test is true") }
}
m = "baz"
test("heyy", text2: "heyy") { (s1, s2) -> Bool in
Swift.print("Value for m is \(m)")
return s1==s2
}
The closure captures m (a variable that is defined in the context in which you define the closure), this means that this will print bar because at the time the closure is executed, the captured m equals to bar. Comment bar-line and baz will be printed; comment baz-line and foo will be printed. The closure captures m, not its value, m by itself, and this is evaluated to the correct value when the closure is evaluated.
Your first function works like this :
arguments :
String 1
String 2
a function that takes two Strings as arguments and returns a Bool
body :
execute the function (flag) with text1 and text2 and check the result.
The function doesn't know at all what you are testing, it only knows that two pieces of text are needed and a Bool will be returned.
So this function allows you to create a general way of handling different functions that all have two Strings as input. You can check for equality or if the first pieces of text is a part of the second and so on.
This is useful for many things and not so far from how array filtering / sorting / map works.
2nd Part :
This is just how you call a function with a closure.
TEST("heyy", text2: "heyy") { (S1, S2) -> Bool in
S1 == S2
}
You can also call it like this :
func testStringEqualityFor(text:String, and:String) -> Bool {
return text == and
}
TEST("hey", text2: "hey", flag: testStringEqualityFor)
Instead of using the trailing closure syntax to pass an unnamed function, you now pass a named function as one of the arguments.
It al becomes a lot clearer when you simplify it.
This is a function that takes another function as an argument.
Now we can call/use this function inside it. The argument function takes a bool as it's argument. So we give it a true
func simpleFunctionWithClosure(closure:(success:Bool) -> Void) {
// use the closure
closure(success: true)
}
When we use the function we need to pass it a function. In Swift you have the trailing closure syntax for that, but that is only available (and even then optional) to the first function as argument.
Trailing closure syntax means that instead of passing a named function you can write:
myFunction { arguments-for-closure-as-tuple -> return-for-closure-as-tuple in
function-body
}
The closure will receive an argument of Bool and returns nothing so Void.
In the body we can handle the arguments and do stuff with them.
But it is important to remember that what is inside the closure is not called directly. It is a function declaration that will be executed by simpleFunctionWithClosure
// use the function
simpleFunctionWithClosure { (success) -> Void in
if success {
print("Yeah")
} else {
print("Ow")
}
}
Or with a named function :
func argumentFunction(success:Bool) -> Void {
if success {
print("Yeah")
} else {
print("Ow")
}
}
simpleFunctionWithClosure(argumentFunction)
Compiler wouldn't have any expectation how your closure is for. For example in your first case, it could not estimate the closure's intake parameters is always just reflect to the first and second parameters of the TEST function when we are always able to write the following code :
func Test(str1:String,str2:String,closure:(String,String)->Bool){
if closure(str[str1.startIndex...str1.startIndex.advanced(2)],str2[str2.startIndex.advanced(1)...str2.endIndex])
{ ... }else{ ... }
//Just an example, everybody know no one write their code like this.
}
The second case, I thought you've just overlooked the syntax sugar:
For a trailing closure A->B:
{ a:A -> B in a.bValue() }
is equal to :
{ a:A -> B in return a.bValue() }
Also, I think this TEST function isn't a good example when the task of it can be done without using closure. I think you can write a map function by yourself for a better understand of why and when to use closure.

What should my Array+RemoveObject.Swift contain?

I am using a template project to try to build a new app. When I run the template project, I get an error saying: '[T] does not have a member named 'indexOf'.
The existing code in the Array+RemoveObject.swift doc is:
import Foundation
public func removeObject<T: Equatable>(object: T, inout fromArray array: [T])
{ let index = array.indexOf(object)
if let index = index {
array.removeAtIndex(index)
}
}
Is the problem the use of indexOf? The odd thing is that when I tried using the solution of someone who answered a similar question, I got around 100 errors from the bond framework.
You function on its own works fine for me (Swift 2.1.1, Xcode 7.2). It seems as if you want this function to be a method of a public class of yours. For a minimum working example, you need at least to wrap your removeObject() method within the class you want it to belong to. Note also that you needn't use a separate line for assigning the result from .indexOf(..) call (possibly nil), but can add assignment and nil check in a single if let statement.
public class MyArrayOperations {
// ...
static public func removeObject<T: Equatable>(object: T, inout fromArray array: [T]) {
if let index = array.indexOf(object) {
array.removeAtIndex(index)
}
}
}
var arr = ["1", "2","3"]
MyArrayOperations.removeObject("2", fromArray: &arr)
print(arr) // ["1", "3"]
Also note that you can explicitly state the same behaviour using two generics, in case you want the array itself to conform to some protocol. You then use one separate generic for the array type and one for its elements, thereafter specifying that the element type should conform to the Generator.Element type of the array. E.g.:
func removeObject<T: Equatable, U: _ArrayType where U.Generator.Element == T>(object: T, inout fromArray array: U) {
if let index = array.indexOf(object) {
array.removeAtIndex(index)
}
}
With this approach, you could add an additional protocol at type constraint for the array generic U in the function signature above, e.g.
func removeObject<T: Equatable, U: protocol<_ArrayType, MyProtocol> where U.Generator.Element == T>(object: T, inout fromArray array: [T]) { ...
This can be especially useful when "simulating" generic Array extensions that conforms to some protocol. See e.g. the following for such an example:
extend generic Array<T> to adopt protocol

Swift infinite loop while iterating array

I have a protocol defined as...
#objc protocol MyDatasource : class {
var currentReportListObjects:[ReportListObject] { get };
}
and some code to iterate the returned array (as an NSArray from ObjC) in Swift as...
if let reportListObjects = datasource?.currentReportListObjects {
for reportListObject:ReportListObject? in reportListObjects {
if let report = reportListObject {
// Do something useful with 'report'
}
}
}
If my reportListObjects array is nil, I get stuck in an infinite loop at the for-loop. Equally, if there is data in the array, it is iterated and 'something useful' is done until the end of my array is reached but the loop is not broken and continues infinitely.
What am I doing wrong? Or is there something blindingly obvious I'm missing here?
You've added a lot of extra Optionals here that are confusing things. Here's what you mean:
for report in datasource?.currentReportListObjects ?? [] {
// Do something useful with 'report'
}
If datasource has a value, this will iterate over its currentReportListObjects. Otherwise it will iterate over an empty list.
If you did want to break it out, rather than using ??, then you just mean this:
if let reportListObjects = datasource?.currentReportListObjects {
for report in reportListObjects {
println(report)
}
}
There's no need for the intermediate reportListObject:ReportListObject? (and that's the source of your problem, since it accepts nil, which is the usual termination of a generator).

How would I properly format this Swift function to map an array?

I'm trying to build a function with swift that will map an array, divide each value in the array by 3, then spit out a new array. This is what I have so far:
func divideby3Map<T, U>(y: [T], z: T -> U) -> [U] {
let array = [int]()
let divideby3Array = array.map { [y] / 3 }
return dividedby3Array
}
divideby3Map([1,2,3,4,5])
Where T and U are the original array, and the new array being returned respectively, and it's done using generics.
I'm sure this isn't written properly, I'm stuck in terms of the right syntax. For example, since the array being returned is represented by the generic [U], I assume I have to use it somewhere in the array being returned, not sure where though.
When writing a generic function, it’s sometimes easier to approach it in 3 steps: first write the code stand-alone using a specific type. Then write the code as a function, still with a specific type. Finally, change the function to be generic.
The first part, dividing an array by 3, can be done like this:
let a = [1,2,3,4,5]
// map is run on the array of integers, and returns a new
// array with the operation performed on each element in a:
let b = a.map { $0 / 3 }
// so b will be [0,0,1,1,1]
// (don’t forget, integer division truncates)
Note the closure you provide between the { } is an operation that will be applied to each element of the array. $0 represents the element, and you divide it by 3. You could also write it as a.map { i in i / 3 }.
To put this into its own function:
func divideby3Map(source: [Int]) -> [Int] {
return source.map { $0 / 3 }
}
No need to declare a fresh array – map will create one for you. You can then return that directly (you can assign it to a temporary if you prefer, but that isn’t really necessary).
Finally, if you want to make it generic, start by adding a placeholder:
func divideby3Map<T>(source: [T]) -> [T] {
return source.map { $0 / 3 }
}
Note, there’s only a need for one placeholder, T, because you are returning the exact same type you are passed in.
Except… this won’t compile, because the compiler doesn’t know that T is guaranteed to provide two critical things: the ability to divide (a / operator), and the ability to create new T from integer literals (i.e. to create a T with value 3 to divide by). Otherwise, what if we passed an array of strings or an array of arrays in?
To do this, we need to “constrain” T so our function will only accept as arguments types that provide these features. One such protocol we can use to constrain T is IntegerType, which does guarantee these features (as well as some other ones like +, * etc):
func divideby3Map<T: IntegerType>(source: [T]) -> [T] {
return source.map { $0 / 3 }
}
divideby3Map(a) // returns [0,0,1,1,1]
let smallInts: [UInt8] = [3,6,9]
divideby3Map(smallInts) // returns [1,2,3]

Resources