Swift NSPopUpButton enum - swift

I'm implementing an NSPopUpButton (for a macOS app using Swift), as in the picture:
And, I have the following code, which actually works:
enum Importance: Int8 {
case EXTREMELY_IMPORTANT = 5
case VERY_IMPORTANT = 4
case IMPORTANT = 3
case NORMAL = 2
case NOT_IMPORTANT = 1
case JUST_FOR_RECORD = 0
case ERROR = -1
}
let english_extremely_important = "Extremely Important"
let english_very_important = "Very Important"
let english_important = "Important"
let english_normal = "Normal"
let english_not_important = "Not Important"
let english_just_for_record = "Just for Record"
var importanceEnglishItems: [String] = {
return [
english_extremely_important,
english_very_important,
english_important,
english_normal,
english_not_important,
english_just_for_record
]
}()
func getImportance(importanceEnglish: String) -> Int8 {
switch importanceEnglish {
case english_extremely_important:
return Importance.EXTREMELY_IMPORTANT.rawValue
case english_very_important:
return Importance.VERY_IMPORTANT.rawValue
case english_important:
return Importance.IMPORTANT.rawValue
case english_normal:
return Importance.NORMAL.rawValue
case english_not_important:
return Importance.NOT_IMPORTANT.rawValue
case english_just_for_record:
return Importance.JUST_FOR_RECORD.rawValue
default:
return Importance.ERROR.rawValue
}
}
Whenever the user selects the item in the popup menu, this code executes:
#IBAction func handleImportancePopUpButtonSelectionChanged(_ importancePopUpButton: NSPopUpButton) {
let importanceIndex = getImportance(importanceEnglish: importancePopUpButton.titleOfSelectedItem!)
print("importanceIndex: \(importanceIndex)")
}
It works, BUT... I believe this implementation isn't that elegant. What is the better way to do this?
I have these requirements in mind:
The corresponding values of the enums list "enum Importance: Int8" are fixed. For example, EXTREMELY_IMPORTANT must be 5, as it is already coded on the server-side. Therefore, based on user's selection, the corresponding enum values must be sent to be server. (EXTREMELY_IMPORTANT == 5, etc.)
Further to the above point, the selection's index of the NSPopUpButton cannot be used for sending to the server. For example, "Extremely Important" would be 0 since it is the first one on the top of the list.
The NSPopUpButton is using "titleOfSelectedItem" and then call getImportance(importanceEnglish: String) method, which is inefficient, and should be better off using "indexOfSelectedItem" instead. That means, it would be more efficient to use the selection index of "Extremely Important" (which is 0) to retrieve the value of 5 for sending to the server.
Better yet, if everything can support support localization (more languages: Japanese, etc.) using standard practice.
How can I make my Swift code more beautiful?

I would change the encapsulation a little bit to make it more readable; such solution would be a better way to start with in my view, (e.g. adding localisation or extending it by new values, etc...).
this idea is obviously not the only way – there are many other alterations/solutions could be as good as this (or maybe even better).
Swift 4.2
enum Importance: Int, CaseIterable {
case extremelyImportant = 5
case veryImportant = 4
case important = 3
case normal = 2
case notImportant = 1
case justForRecord = 0
var friendlyName: String? {
switch self {
case .extremelyImportant: return "Extremely Important"
case .veryImportant: return "Very Important"
case .important: return "Important"
case .notImportant: return "Not Important"
case .justForRecord: return "Just for Record"
default: return nil
}
}
init?(withName name: String) {
guard let importance = Importance.allCases.first(where: {
guard let friendlyName = $0.friendlyName else { return false }
return friendlyName == name
}) else { return nil }
self = importance
}
static var allCasesNames: [String] {
return Importance.allCases.compactMap { $0.friendlyName }
}
}

You can create NSMenuItem with a Title and importance as tag and add it NSPopUpButton.menu.items.
override func viewDidLoad() {
super.viewDidLoad()
popUpButton.menu?.items = self.importanceEnglishItems
}
class func MenuItem(title: String, tag: Int) -> NSMenuItem {
let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")
item.tag = tag
return item
}
var importanceEnglishItems: [NSMenuItem] = {
return [
MenuItem(title: "Extremely Important", tag: 5),
MenuItem(title: "Very Important", tag: 4),
MenuItem(title: "Important", tag: 3),
MenuItem(title: "Normal", tag: 2),
MenuItem(title: "Not Important", tag: 1),
MenuItem(title: "Just for Record", tag: 0)
]
}()
#IBAction func handleSelection(_ sender: NSPopUpButton) {
guard let item = sender.selectedItem else { return }
print("importanceIndex: \(item.tag)")
}

Related

Forwarding function generic parameter to generic class type

I have created enum with associated value and I want to be able to dynamically update associated value. As far as I know Swift doesn't support that at the moment.
Because of that I used following approach:
enum PersonInfo {
class EnumValue<T> {
var value: T
init(_ value: T) {
self.value = value
}
}
// Instead of using String or Bool or any other type directly, use EnumValue wrapper
case firstName(EnumValue<String>)
case lastName(EnumValue<String>)
case isAdult(EnumValue<Bool>)
}
I want to add function that would update EnumValue.value property in following way:
func updateAssociatedValue<V>(_ updateValue: V) {
let mirror = Mirror(reflecting: self)
for associatedValue in mirror.children {
guard let value = associatedValue.value as? EnumValue<V> else {
continue
}
value.value = updateValue
}
}
Problem is that this guard statement always fails (guard let value = associatedValue.value as? EnumValue<V>) and I can't figure it out why.
On the other hand, when I write updateAssociatedValue with typed type then things work properly:
// This works
func updateAssociatedValue(_ updateValue: String) {
let mirror = Mirror(reflecting: self)
for associatedValue in mirror.children {
guard let value = associatedValue.value as? EnumValue<String> else {
continue
}
value.value = updateValue
}
}
Things compile normally but during the runtime guard statement always fails. Am I using generic value in some incorrect way? Should I use somehow updateValue.Type or updateValue.self (I tried but it didn't work).
Example of usage:
var array: [PersonInfo] = [
.firstName(PersonInfo.EnumValue("John")),
.lastName(PersonInfo.EnumValue("Doe")),
.isAdult(PersonInfo.EnumValue(false))
]
print(array)
// John, Doe, false
array.first?.updateAssociatedValue("Mike")
print(array)
// Mike, Doe, false
I can always reassign enum value in array but if possible I want to avoid that. That's the reason for asking this question.

RXSwift ObservableCollection with CombineLatest

I am trying to implement something like this,
let api1 = Observable.of(["documents"]) //Replace with observable to download docs
let api2 = Observable.of(["applications"]) //Replace with observable to download apps
let api3 = Observable.of(["videos"]) //Replace with observable to download videos
Observable.combineLatest(api1, api2, api3){(docs, apps, videos) in
return (docs, apps, videos)
}.skipWhile{ (docs, apps, videos) in
return docs.count == 0 && apps.count == 0 && videos.count == 0
}.subscribe(onNext:{(docs, apps, videos) in
})
.disposed(by:disposeBag)
In my case, I am trying to create observables dynamically and add it to an array like this,
private var discoverObservables = [Observable<Any>]()
func loadDiscoverFeeds(){
self.feeds.forEach({
feed in
switch feed.feedType{
case "a":
let observable = self.aObservable(url: feed.feedURL ?? "")
self.discoverObservables.append(observable)
break
case "b":
let observable = self.bObservable(url: feed.feedURL ?? "")
self.discoverObservables.append(observable)
break
case "c":
let observable = self.cObservable(url: feed.feedURL ?? "")
self.discoverObservables.append(observable)
break
case "d" :
let observable = self.dObservable(url: feed.feedURL ?? "")
self.discoverObservables.append(observable)
break
default:
break
}
})
}
private func aObservable(url : String) -> Observable<A?>{
return APIManager.shared.getA(url: url)
}
private func bObservable(url : String) -> Observable<B?>{
return APIManager.shared.getB(url: url)
}
private func cObservable(url : String) -> Observable<C?>{
return APIManager.shared.getC(url: url)
}
But this is not working because discoverObservables array is expecting the value of Type Observable<Any> and I am trying to add Observable<A?>
How can I do this correctly, I want to make sure all the observables return data before I start processing the data.
Edit
I am trying to load data from different sources before that is added to the view, basically, I have a collectionview, each section loads data from different API, I am trying to get all the required data from all sources before that is added to collection view.
Add the same protocol to A, B and C.
protocol YourProtocol {...}
class A: YourProtocol {...}
class B: YourProtocol {...}
class C: YourProtocol {...}
Then you can make :
private var discoverObservables = [Observable<YourProtocol>]()
The first code block seems to be doing the job with one exception, the condition checks if all of the (docs, apps, videos) are empty, perhaps you wanted to use || instead of &&.
As for the second code block with an array, I did something that could help.
struct A {}
let observable1 = Observable.just(A())
let observable2 = Observable.just(A())
let observable3 = Observable.just(A())
let observables: [Observable<A>] = [observable1, observable2, observable3]
Observable.combineLatest(observables).skipWhile { (streams) -> Bool in
streams.forEach {
if $0.count == 0 { return true }
}
return false
}.subscribe(...
This subscription will result with Observable<[A]>.
I'm going to specifically address this from your question: "I want to make sure all the observables return data before I start processing the data."
Strictly speaking, you probably don't want an Any structure. Better would be a protocol or enum. I see that other answers have addressed the protocol idea so I will use the enum idea:
enum EndpointResponse {
case a(A?)
case b(B?)
// etc...
}
let responses = Observable.zip(
feeds.map { (feed) -> Observable<EndpointResponse> in
switch feed.feedType {
case "a":
return aObservable(url: feed.feedURL ?? "").map { EndpointResponse.a($0) }
case "b":
return bObservable(url: feed.feedURL ?? "").map { EndpointResponse.b($0) }
default:
fatalError()
}
}
)
The above responses observable will contain an array of all the responses once they have all emitted values. In other words, the zip operator will gather up all the responses from all the network calls and emit a single array containing all of them.
My Previous answer:
There really isn't a lot of information to go on in the question, but something like this answers the direct question you ask about converting an Observable<X> to an Observable<Any>...
let discoverObservables = Observable.zip(
feeds.map { (feed) -> Observable<Any> in
switch feed.feedType {
case "a":
return aObservable(url: feed.feedURL ?? "").map { $0 as Any }
case "b":
return bObservable(url: feed.feedURL ?? "").map { $0 as Any }
case "c":
return cObservable(url: feed.feedURL ?? "").map { $0 as Any }
case "d":
return dObservable(url: feed.feedURL ?? "").map { $0 as Any }
default:
break
}
}
)

How can you do a simple inline test for an enumeration's case that has associated values you don't care about?

Given this code:
class Item{}
func foo(item:Item){}
enum SelectionType{
case single(resultsHandler:(Item)->Void)
case multi(resultsHandler:([Item])->Void)
}
var selectionType:SelectionType = .single(resultsHandler:foo)
// This line won't compile
let title = (selectionType == .single)
? "Choose an item"
: "Choose items"
How can you update the part that won't compile?
A ternary operator cannot work for enums with associated values, because the classic equality operator does not work with them. You have to use pattern matching, or if case syntax:
let title: String
if case .single = selectionType {
title = "Choose an item"
} else {
title = "Choose items"
}
I don't know if there is a direct way to address what you are looking for.
My understanding:
Enums are not equatable by default, you have to implement Equatable
For enums with associated values, even if you implemented it, I don't think it is possible to achieve what you had asked.
Computed variable (Workaround 1):
enum SelectionType{
case single(resultsHandler:(Item)->Void)
case multi(resultsHandler:([Item])->Void)
var title : String {
let text : String
switch self {
case .single(_):
text = "Choose an item"
case .multi(_):
text = "Choose items"
}
return text
}
}
var title = selectionType.title
Use if case (Workaround 2):
if case .single(_) = selectionType {
print("Choose an item")
}
else {
print("Choose items")
}

Find element with the same title and return class-element

The Class Book is what I'm struggling on. The goal is to turn the exam block to true.
I try to compare the title of every book in the liste-array with the title I´m searching for. If it´s found the function should output the book-element and if not, return nil.
This is what I currently have:
class Book {
var title:String;
var isbn:String;
var price:Float;
public init(_ title:String, _ isbn:String, _ price:Float) {
self.title=title;
self.isbn=isbn;
self.price=price;
}
}
//findBookWithTitle should output the first element with the same title.
func findBookWithTitle(_ title:String, inListe liste:[Book]) -> Book? {
var data=liste;
var stitle=title;
var memory:Int=0;
for i in 0..<data.count{
if data[i].title==stitle{
memory=i;
}else{
return nil;
}
}
return data[memory]
}
//exam block
let daten=[Book("Book A","ISBN A",12),Book("Buch B","ISBN B",14),Book("Book C","ISBN C",17)];
let a1a = findBookWithTitle("Book C", inListe: daten) === daten[2];
let a1b = findBookWithTitle("Book A", inListe: daten) === daten[0];
let a1c = findBookWithTitle("Testbook", inListe: daten) === nil;
let a1 = a1a && a1b && a1c;
I don´t have any errors and don't know where to start fixing the problem.
Your code does not work because you return nil as soon as a non-matching book title is encountered during the enumeration.
The correct approach is to return as soon as a book with a matching title is found, and to return nil if no matching book was found during
the enumeration:
func findBookWithTitle(_ title:String, inListe liste:[Book]) -> Book? {
for i in 0..<liste.count {
if liste[i].title == title {
return liste[i]
}
}
return nil
}
(Note that there is no need to make variable copies of all the parameters.)
As already suggested above, this can be simplified to
func findBookWithTitle(_ title:String, inListe liste:[Book]) -> Book? {
return liste.first(where: { $0.title == title })
}
using the first(where:) method for arrays (or more generally, for sequences).

How to access a Swift enum associated value outside of a switch statement

Consider:
enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
}
let leftEdge = Line.Horizontal(0.0)
let leftMaskRightEdge = Line.Horizontal(0.05)
How can I access, say, lefEdge's associated value, directly, without using a switch statement?
let noIdeaHowTo = leftEdge.associatedValue + 0.5
This doesn't even compile!
I had a look at these SO questions but none of the answers seem to address this issue.
The noIdeaHowTo non compiling line above should really be that one-liner, but because the associated value can be any type, I fail to even see how user code could write even a "generic" get or associatedValue method in le enum itself.
I ended up with this, but it is gross, and needs me to revisit the code each time I add/modify a case ...
enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
var associatedValue: CGFloat {
get {
switch self {
case .Horizontal(let value): return value
case .Vertical(let value): return value
}
}
}
}
Any pointer anyone?
As others have pointed out, this is now kind of possible in Swift 2:
import CoreGraphics
enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
}
let min = Line.Horizontal(0.0)
let mid = Line.Horizontal(0.5)
let max = Line.Horizontal(1.0)
func doToLine(line: Line) -> CGFloat? {
if case .Horizontal(let value) = line {
return value
}
return .None
}
doToLine(min) // prints 0
doToLine(mid) // prints 0.5
doToLine(max) // prints 1
You can use a guard statement to access the associated value, like this.
enum Line {
case Horizontal(Float)
case Vertical(Float)
}
let leftEdge = Line.Horizontal(0.0)
let leftMaskRightEdge = Line.Horizontal(0.05)
guard case .Horizontal(let leftEdgeValue) = leftEdge else { fatalError() }
print(leftEdgeValue)
I think you may be trying to use enum for something it was not intended for. The way to access the associated values is indeed through switch as you've done, the idea being that the switch always handles each possible member case of the enum.
Different members of the enum can have different associated values (e.g., you could have Diagonal(CGFloat, CGFloat) and Text(String) in your enum Line), so you must always confirm which case you're dealing with before you can access the associated value. For instance, consider:
enum Line {
case Horizontal(CGFloat)
case Vertical(CGFloat)
case Diagonal(CGFloat, CGFloat)
case Text(String)
}
var myLine = someFunctionReturningEnumLine()
let value = myLine.associatedValue // <- type?
How could you presume to get the associated value from myLine when you might be dealing with CGFloat, String, or two CGFloats? This is why you need the switch to first discover which case you have.
In your particular case it sounds like you might be better off with a class or struct for Line, which might then store the CGFloat and also have an enum property for Vertical and Horizontal. Or you could model Vertical and Horizontal as separate classes, with Line being a protocol (for example).
Why this is not possible is already answered, so this is only an advice. Why don't you implement it like this. I mean enums and structs are both value types.
enum Orientation {
case Horizontal
case Vertical
}
struct Line {
let orientation : Orientation
let value : CGFloat
init(_ orientation: Orientation, _ value: CGFloat) {
self.orientation = orientation
self.value = value
}
}
let x = Line(.Horizontal, 20.0)
// if you want that syntax 'Line.Horizontal(0.0)' you could fake it like this
struct Line {
let orientation : Orientation
let value : CGFloat
private init(_ orientation: Orientation, _ value: CGFloat) {
self.orientation = orientation
self.value = value
}
static func Horizontal(value: CGFloat) -> Line { return Line(.Horizontal, value) }
static func Vertical(value: CGFloat) -> Line { return Line(.Vertical, value) }
}
let y = Line.Horizontal(20.0)
You can get the associated value without using a switch using the if case let syntax:
enum Messages {
case ping
case say(message: String)
}
let val = Messages.say(message: "Hello")
if case let .say(msg) = val {
print(msg)
}
The block inside the if case let will run if the enum value is .say, and will have the associated value in scope as the variable name you use in the if statement.
With Swift 2 it's possible to get the associated value (read only) using reflection.
To make that easier just add the code below to your project and extend your enum with the EVAssociated protocol.
public protocol EVAssociated {
}
public extension EVAssociated {
public var associated: (label:String, value: Any?) {
get {
let mirror = Mirror(reflecting: self)
if let associated = mirror.children.first {
return (associated.label!, associated.value)
}
print("WARNING: Enum option of \(self) does not have an associated value")
return ("\(self)", nil)
}
}
}
Then you can access the .asociated value with code like this:
class EVReflectionTests: XCTestCase {
func testEnumAssociatedValues() {
let parameters:[EVAssociated] = [usersParameters.number(19),
usersParameters.authors_only(false)]
let y = WordPressRequestConvertible.MeLikes("XX", Dictionary(associated: parameters))
// Now just extract the label and associated values from this enum
let label = y.associated.label
let (token, param) = y.associated.value as! (String, [String:Any]?)
XCTAssertEqual("MeLikes", label, "The label of the enum should be MeLikes")
XCTAssertEqual("XX", token, "The token associated value of the enum should be XX")
XCTAssertEqual(19, param?["number"] as? Int, "The number param associated value of the enum should be 19")
XCTAssertEqual(false, param?["authors_only"] as? Bool, "The authors_only param associated value of the enum should be false")
print("\(label) = {token = \(token), params = \(param)")
}
}
// See http://github.com/evermeer/EVWordPressAPI for a full functional usage of associated values
enum WordPressRequestConvertible: EVAssociated {
case Users(String, Dictionary<String, Any>?)
case Suggest(String, Dictionary<String, Any>?)
case Me(String, Dictionary<String, Any>?)
case MeLikes(String, Dictionary<String, Any>?)
case Shortcodes(String, Dictionary<String, Any>?)
}
public enum usersParameters: EVAssociated {
case context(String)
case http_envelope(Bool)
case pretty(Bool)
case meta(String)
case fields(String)
case callback(String)
case number(Int)
case offset(Int)
case order(String)
case order_by(String)
case authors_only(Bool)
case type(String)
}
The code above is from my project https://github.com/evermeer/EVReflection
https://github.com/evermeer/EVReflection