An Any and AnyObject Difference
if an Any Declare
let anyValues: [Any] = [1, "two", 3, "four", ["name": "praveen"]]
anyValues.forEach { (anyValue) in
switch anyValue {
case is Int:
print("\(anyValue) is an Int!")
case is String:
print("\(anyValue) is String!")
case is [String: Any]:
print("\(anyValue) is Discnary!")
default:
print("\(anyValue) is de!")
}
}
Output =>
1 is an Int!
two is String!
3 is an Int!
four is String!
["name": "praveen"] is Discnary!
if an AnyObject Declare
let anyValues: [AnyObject] = [1, "two", 3, "four", ["name": "praveen"]]
Error==> Type of expression is ambiguous without more context
Custom Higher Order Function Filter Even Number
func coustomFilterNumber<T>(_ inputArray: [T], _ condition: (T) -> Int)-> [T]{
var result = [T]()
for element in inputArray{
if (condition(element) != 0){
result.append(element)
}
}
return result
}
let nums = [2, 5, 10, 4, 6, 7, 11]
let num = coustomFilterNumber(nums, {$0 % 2})
print(num)
Output -- > [5, 7, 11]
Custom function to apply multiple conditions?
struct Person {
let name: String
let age: Int
let isEmp: Bool
}
func EmpFilter(_ persons: [Person], _ filters: [(Person) -> Bool]) -> [Person]{
var result: [Person] = []
for person in persons{
var shouldInc = true
for filter in filters{
if !filter(person){
shouldInc = false
break
}
}
if shouldInc{
result.append(person)
}
}
return result
}
let people = [
Person(name: "Alexander", age: 28, isEmp: true),
Person(name: "Bob", age: 22, isEmp: false),
Person(name: "Catalina", age: 35, isEmp: true),
Person(name: "Diana", age: 40, isEmp: false),
Person(name: "Emly", age: 19, isEmp: true)
]
let filter: [(Person) -> Bool] = [
{$0.age > 25},
{$0.isEmp},
{$0.name.count > 5}
]
let filterPeson = EmpFilter(people, filter)
for feson in filterPeson{
print("\(feson.name), Age: \(feson.age), Employed: \(feson.isEmp)")
}
Comments
Post a Comment