So I'm very new to Swift at the moment and am working on a class (as below).
The variable selectedOption
can be an array of String
or Int
and the methods need to compare the values received against that array.
The below code works, but I don't like the fact that I'm type checking and replicating the code to compare Strings then again to compare Ints in methods isSelected
and removeSelectedItem
Such as
if selectedOption is String {
return (self.selectedOption!.indexOf({ $0 as! String == selectedOption as! String }) != nil)
} else if ( selectedOption is Int ) {
return (self.selectedOption!.indexOf({ $0 as! Int == selectedOption as! Int })) != nil
}
There must be a better way?
public class SearchOption {
private var title: String
private var allowAny: Bool
private var allowMultiple: Bool
private var dependencies: [SearchOption]?
// Store the selected Item in an array of AnyObjects.
private var selectedOption: [AnyObject]?
init(title: String, allowAny: Bool, allowMultiple: Bool, dependencies: [SearchOption]?) {
self.title = title
self.allowAny = allowAny
self.allowMultiple = allowMultiple
self.dependencies = dependencies
}
public func setSelectedItem(selectedOption: AnyObject) -> Void {
if self.selectedOption == nil || !self.allowMultiple{
self.selectedOption = [AnyObject]()
}
self.selectedOption?.append(selectedOption)
}
public func getSelectedItem() -> [AnyObject]? {
return self.selectedOption
}
public func removeSelectedItem(selectedOption: AnyObject) -> Void {
if self.selectedOption != nil {
if selectedOption is String {
self.selectedOption = self.selectedOption!.filter() { $0 as! String != selectedOption as! String }
} else if ( selectedOption is Int ) {
self.selectedOption = self.selectedOption!.filter() { $0 as! Int != selectedOption as! Int }
}
}
}
public func isSelected(selectedOption: AnyObject) -> Bool {
if self.selectedOption != nil {
if selectedOption is String {
return (self.selectedOption!.indexOf({ $0 as! String == selectedOption as! String }) != nil)
} else if ( selectedOption is Int ) {
return (self.selectedOption!.indexOf({ $0 as! Int == selectedOption as! Int })) != nil
}
}
return false
}
public func clearSelectedItems() -> Void {
self.selectedOption = nil
}
public func checkDependencies() -> Bool {
if dependencies != nil {
for dependency in dependencies! {
if dependency.getSelectedItem() == nil {
return false
}
}
}
return true
}
}
var make: SearchOption = SearchOption(title: "Make", allowAny: true, allowMultiple: true, dependencies: nil)
make.setSelectedItem("Vauxhall")
make.setSelectedItem("Mazda")
make.setSelectedItem("Audi")
print(make.getSelectedItem())
make.removeSelectedItem("Mazda")
print(make.getSelectedItem())
print(make.isSelected("Audi"))
Outputs:
Optional([Vauxhall, Mazda, Audi])
Optional([Vauxhall, Audi])
true