How to get index of an item in a array? [closed] - ios

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
What is the most efficient way to get the index of an item in array? In Objective-C we used to be able to do:
[arrayName indexOfObject:myObject]
in Swift, I know we can do the following.
index =arrayName.indexOf({$0 === myObject})
is this the cleanest and most efficient way to do it?

As Oliver pointed out, you can use
let index = array.indexOf(myObject)
However, this will only work if your object conforms to the Equatable protocol, to conform to it, you have to implement the == function, like this:
class MyClass {
}
extension MyClass: Equatable { }
func ==(lhs: MyClass, rhs: MyClass) -> Bool {
return lhs === rhs // === returns true when both references point to the same object
}
If your class inherits from NSObject and your comparison is something other than just comparing pointers, you'll have to override isEqual: as well
override func isEqual(object: AnyObject?) -> Bool {
guard let obj = object as? MyClass else { return false }
return self == obj
}

You can use:
let index = array.indexOf(myObject)
You don't need to use the closure as indexOf accepts the element itself as an argument
Bear in mind that index is optional though

Related

What is better in this case: extension or function? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 months ago.
Improve this question
I have a ViewController where there's a logic for the "known" and "unknown" location.
At a high level it looks like this:
class MyViewController {
private var myVar: CLLocationCoordinate2D? // is updated somewhere
private var myFunc1() {
let someCond = myVar == nil // "isLocationUnknown" logic
}
private var myFunc2() {
guard let myVar == nil else { return } // "isLocationUnknown" logic
}
}
Now there's a requirement to handle the "invalid location" case.
Which means in addition to the nullability check, the CLLocationCoordinate2D check should be performed.
And I can't decide what is better ( as I don't know where to learn about Swift implementation details except of reading the sources :) ) :
Approach #1:
private func isLocationUnknown(_ location: CLLocationCoordinate2D?) -> Bool {
guard let location = location else {
return true
}
return !CLLocationCoordinate2DIsValid(location)
}
Approach #2:
private extension Optional where Wrapped == CLLocationCoordinate2D {
var isUnknown: Bool {
guard let self = self else {
return true
}
return !CLLocationCoordinate2DIsValid(self)
}
}
The criterias of comparison:
semantics: I guess #2 is more "swifty"/expressive etc
compilation time: can there be any difference (at scale)?
run-time performance: can there be any difference (at scale)?
I believe in this particular case all criterias are not important, but if this enum would be public, and called e.g. many times per second, or within multiple places in the codebase, then I'd like to be more confident when making the decision.
A class and func are reference types and stored on the heap and is therefore slower to access. Since the type Optional is an enum it is stored on the stack and will be quicker to access. But in this case it would probably not be a noticeable difference. Do which ever you feel is right.
If you want to read about memory management, here's a good article:
https://manasaprema04.medium.com/memory-management-in-swift-heap-stack-arc-6713ca8b70e1m
And here is a question about stack vs. heap memory:
Swift stack and heap understanding
EDIT:
Another thought is that your first approach takes CLLocationCoordinate2D as a parameter which creates a new copy of CLLocationCoordinate2D. So the space complexity is probably larger as well. But if that's the case, minuscule.

How to keep track of previous value of variable in swift? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I am trying keep track of previously selected row index of tableview inside sideMenu.
Here is a simple and reliable solution. Use the willSet property observer to keep track of the previous value of a variable.
var previousSelectedIndex: IndexPath?
var selectedIndex: IndexPath? {
willSet {
previousValue = selectedIndex
}
}
Use the selectedIndex variable to keep track of the current selected index which you can get from your didSelect delegate.
var previousSelectedIndex = 0
var currentSelectedIndex = 0 {
didSet {
print("===>current", currentSelectedIndex)
print("===>previous", previousSelectedIndex)
}
willSet {
previousSelectedIndex = self.currentSelectedIndex
}
explanation: didSet and willSet is property Observer in swift
didset is use to get current value of variable and will set is use to get previous value of variable .
IF you want to learn more detail about propertyObserver refer this link
https://medium.com/the-andela-way/property-observers-didset-and-willset-in-swift-4-c3730f26b1e9

How dynamically initialise object in Swift 3 [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I use below line of code to allocate an Object(Suppose my Object name is Car) dynamically.
[self initliazieObject:[Car class]]
- (id)initliazieObject:(Class)model{
id record = [[model alloc] init];
return record;
}
How I can do this in swift 3.
Exactly as in Objective-C. Try this in a playground:
class Car : NSObject {}
func factory(type:NSObject.Type) -> NSObject {
return type.init()
}
let c = factory(type:Car.self)
print(type(of:c)) // Car
(We can get fancy and do clever things with generics or Self to specify the type of the returned object more precisely, but my goal in this code is simply to do things the dumb way, just like Objective-C.)

When do I want to use static, final, private in swift 2.2? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I kind of know when to use those different keywords, but can someone clarify for me when exactly do I want to use them, and how do they affect my apps during runtime?
static
You use a static method or property when you need some data without allocating new object, the most common use of static could be the singleton design pattern or when you have some helper class.
So for example in a function you can call:
let temp = Helper.staticMethod();
where
class Helper {
private let test1234 = false
private func privateMethod() {
}
private static func privateStaticMethod() -> Int {
return 0
}
static func staticMethod() -> Int {
self.privateMethod() // Error
self.test1234 // Error
self.test1234 // Error
Helper.privateStaticMethod() // OK
return 0
}
}
from staticMethod you can't have the access to NOT static method or property of the class Helper
final
It should be best practice declare all classes final and remove it just if you have to subclass them. Final provides you a compile time error if you try to subclass a final class and so this can help you to have a clean architecture without risking to create messy code and it help the readability of the code as well.
final class FinalClass {
}
class Sub1: FinalClass {
} //Error
class Base {
}
class SubBase: Base {
} //OK
private
A private class / property is not visible outside the scope.
It helps you to have a good encapsulation in your architecture.
class A {
private let test = 1
let test2 = 1
}
let classA = A()
classA.test //Error
classA.test2 //OK
I suggest reading the Swift documentation for better explanations:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Inheritance.html
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/AccessControl.html
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Methods.html

call methode from one class in another (swift) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
What I want to do is create a method in one class of my iOS app and then call that method from other classes in my app. Could someone explain exactly what I need to do to achieve this? Any help would be greatly appreciated as all my attempts so far have failed!
Thanks.
class Principle
{
var name:String = ""
func get_name() -> String
{
return self.name
}
}
class School
{
var princ:Principle = Principle()
init()
{
princ.name = "Mike"
println(princ.get_name())
}
}
class MyClass : OptionalSuperClass, OptionalProtocol1 {
var myProperty:String
var myOptionalProperty:String?
// More properties...
func doIt(a:Int) -> Int {
return a
}
var a = MyClass()
a.doIt(1)

Resources