Search
 
SCRIPT & CODE EXAMPLE
 

SWIFT

compactMap


///lets say we have array of string which contains Int value but we are not sure about that
///all the elements can convert into int because we some element can't be int


var array = ["3", "data", "2", "5", "23", "hello"]


var simpleMapResult: [Int?] = array.map { elment in
    return Int(elment)
}
print("The original array => ")
print(array)
print("
After maping through we'll see the result is option int array =>")
print(simpleMapResult)

///Next task is make them no-optional and remove nil

var simpleMapRemovedNil: [Int?] = simpleMapResult.filter { element in
    return element != nil
}
print("
Now we have array of int which does not have nil value")
print(simpleMapRemovedNil)

//Now make them non-optional

var simpleMapNonOptional: [Int] = simpleMapRemovedNil.map { element in
    return element!
}

print("
Now we have array of non-optional int")
print(simpleMapNonOptional)


/// not the simple approch is compactMap

var compactMapNonOptional: [Int] = array.compactMap { elment in
    return Int(elment)
}
print("
Compact map output")
print(compactMapNonOptional)



/* Output is
The original array => 
["3", "data", "2", "5", "23", "hello"]

After maping through we'll see the result is option int array =>
[Optional(3), nil, Optional(2), Optional(5), Optional(23), nil]

Now we have array of int which does not have nil value
[Optional(3), Optional(2), Optional(5), Optional(23)]

Now we have array of non-optional int
[3, 2, 5, 23]

Compact map output
[3, 2, 5, 23]
*/
Comment

PREVIOUS NEXT
Code Example
Swift :: waiting for all the threads to finish swift 
Swift :: swift print struct name 
Swift :: swift function 
Swift :: swift increase int value 
Swift :: multiline comment in swift 
Swift :: Swfit Add Elements to an Array 
Swift :: Swift guard Statement Inside a Function 
Swift :: swift if let 
Swift :: ios swift local storage with icloud 
Swift :: Why Inheritance? 
Swift :: swift constants 
Swift :: weather api in ios swift 5 
Swift :: swift how to dereference unsafemutablepointer 
Swift :: Typealias for built-in types 
Swift :: Swift Variables names must start with either a letter 
Swift :: key path expression as functions ios swift 
Swift :: swift animate constraint 
Swift :: Swift Create Multiple Objects of Class 
Swift :: declare empty dictionary in swift 
Ruby :: rails get list of tables 
Ruby :: ruby filename from path 
Ruby :: how to decrypt credentials in rails 
Ruby :: ruby reference a file in a gem 
Ruby :: substring replace in ruby 
Ruby :: get date millis rails 
Ruby :: list ruby versions 
Ruby :: sort array of hashes ruby 
Ruby :: ruby loop through array 
Ruby :: rails render head: :ok 
Ruby :: rails debug 
ADD CONTENT
Topic
Content
Source link
Name
4+2 =