Post

Replies

Boosts

Views

Activity

String interpolation produces a debug description for an optional value; did you mean to make this explicit?
This makes my head dizzy! Help me out of this peril. How to avoid this with my own class objects? let obj: LanguageItem? = LanguageItem(language: "en") print("object: \(obj)") struct LanguageItem: Codable { var language: String var name: String? } extension LanguageItem: CustomStringConvertible { var description: String { "Lang:\(language) name:\(name ?? "(none)")" } } The print statement still prints "Optional(Lang:en name:(none))". How to get rid the Optional prefix?
2
0
561
Aug ’23
Does Swift support stored property with computed value?
This may sound strange, but I encounter real world need on this. private var queryItems_: [URLQueryItem]? private var queryItems: [URLQueryItem]? { get { if queryItems_ == nil { if !queries.isEmpty { queryItems_ = queries.map { (key: String, value: String?) in return URLQueryItem(name: key, value: value) } } } return queryItems_ } } /// Query strings public private(set) lazy var queries = [String: String?]() { didSet { queryItems_ = nil } } The queryItems will be (re)created on get if queries property was changed. What I wish is that I could use queryItems as a simple var property but let me do my logic in its getter. Is this supported already?
1
0
345
Aug ’23
How throw error in willSet
I have the following code: public var endpoint: String! { willSet { if newValue == nil { throw ErrorCode.NullValue("endpoint") } } } But compiler gives me error: Error is not handled because the enclosing function is not declared 'throws'
3
0
791
Aug ’23
How extract files in Assets.car?
I got a few answers from SO, but the tools are too old and they don't even run my macOS (12.6). Is there any official way to extract an Assets.car file? The reason I ask this question is that I want to re-use the icons for strings/storyboard files in Xcode packaged Assets.car (if it's legal).
0
0
1k
Sep ’23
Ensure value in a Dictionary
In many cases, I need to get the value from a dictionary given a key (usually a string). I have the following helper class: public class ObjectCache<T> { private var cache = [String: T]() subscript(name: String) -> T? { get { return cache[name] } set { cache[name] = newValue } } func get(_ name: String, with builder: () -> T?) -> T? { var obj = cache[name] if obj == nil { obj = builder() cache[name] = obj } return obj } } This saves much keyboard typing and avoid common errors of oversight. Like below: let serviceURL = self.urlCache.get(name) { return comp.url }! Now my question is - Does Swift provide some builtin functionality like this? I just hope I did not re-event the wheel.
1
0
375
Sep ’23
switch case and === operator
I have the following code: func numberOfRows(in tableView: NSTableView) -> Int { switch tableView { case self.stringsTable: return self.stringsList?.count ?? 0 case self.localeTable: return self.localeMap.count default: print("numberOfRows not handled for \(tableView)") return 0 } } I wonder if there is any (performance) difference between case and ==== operator like below: func numberOfRows(in tableView: NSTableView) -> Int { if tableView === self.stringsTable { } // ... }
3
0
490
Sep ’23
Extension method for Optional of String
I came across an article about extension of Optional (https://useyourloaf.com/blog/empty-strings-in-swift/), but I cannot get it to work for the Optional extension. extension Optional where Wrapped == String { var isBlank: Bool { return self?.isBlank ?? true } } func testIsBlank() { for s in [nil, "", " ", "\t", "abc"] { print(s?.isBlank) } } For nil value, the output is still nil. I see the article is quite old dated back in 2019. There must be some changes in the language specs. What's going on here?
1
0
685
Sep ’23
Symbol navigator is polluted with thousands of system classes!
I have a test app. I added some extension classes to one of source code like below: extension String { func addPathComponent(_ path: String) -> String { return (self as NSString).appendingPathComponent(path) } func sameText(with: String) -> Bool { return self.caseInsensitiveCompare(with) == .orderedSame } var isBlank: Bool { allSatisfy { $0.isWhitespace } } } extension Optional where Wrapped == String { var isBlank: Bool { self?.isBlank ?? true } } Now the symbol navigator is polluted with many system classes: BTW, I am using Xcode 14.3.1.
1
0
628
Sep ’23
Any way to get array by reference?
Today I spent one hour to get myself educated on Array type. I have the following class in one of my app: class PathNode: Hashable, Comparable, CustomStringConvertible { var name: String! var path: String! var children: [PathNode]? static func == (lhs: PathNode, rhs: PathNode) -> Bool { lhs.name == rhs.name } static func < (lhs: PathNode, rhs: PathNode) -> Bool { lhs.name < rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(children) } /// Sort child nodes. func sort() { if let children = self.children { children.sort() for child in children { child.sort() } } } // other members... } The problem is in the sort function. I found out in my outline view the result is not sorted even though I did call sort on the root node. After about one hour's frustration, I came to realize that I forgot one import fact about the array type in Swift - it's a value type! I have to adjust sort function to the following code: /// Sort child nodes. func sort() { if self.children != nil { self.children!.sort() for child in self.children! { child.sort() } } } That's not an elegant way of writing code! Is there any other way to get a 'reference' to an array in Swift?
2
0
429
Sep ’23
String interpolation produces a debug description for an optional value; did you mean to make this explicit?
This makes my head dizzy! Help me out of this peril. How to avoid this with my own class objects? let obj: LanguageItem? = LanguageItem(language: "en") print("object: \(obj)") struct LanguageItem: Codable { var language: String var name: String? } extension LanguageItem: CustomStringConvertible { var description: String { "Lang:\(language) name:\(name ?? "(none)")" } } The print statement still prints "Optional(Lang:en name:(none))". How to get rid the Optional prefix?
Replies
2
Boosts
0
Views
561
Activity
Aug ’23
Linker errors in Swift app with a framework bundle
I have a simple test project which has a framework bundle (as a target). See attached screenshots. When I import MyFramework and use classes from the framework, the app compiles fine but got linker errors. It seems Xcode does not automatically link the bundle into the app.
Replies
2
Boosts
0
Views
574
Activity
Aug ’23
Does Swift support stored property with computed value?
This may sound strange, but I encounter real world need on this. private var queryItems_: [URLQueryItem]? private var queryItems: [URLQueryItem]? { get { if queryItems_ == nil { if !queries.isEmpty { queryItems_ = queries.map { (key: String, value: String?) in return URLQueryItem(name: key, value: value) } } } return queryItems_ } } /// Query strings public private(set) lazy var queries = [String: String?]() { didSet { queryItems_ = nil } } The queryItems will be (re)created on get if queries property was changed. What I wish is that I could use queryItems as a simple var property but let me do my logic in its getter. Is this supported already?
Replies
1
Boosts
0
Views
345
Activity
Aug ’23
Does Swift provide conventional standard error classes/enums?
I could not find any standard error classes/enums in docs. For example, I have the following error situations: Invalid null parameter Parameter value out of range Property value (of T!) not set
Replies
2
Boosts
0
Views
527
Activity
Aug ’23
How throw error in willSet
I have the following code: public var endpoint: String! { willSet { if newValue == nil { throw ErrorCode.NullValue("endpoint") } } } But compiler gives me error: Error is not handled because the enclosing function is not declared 'throws'
Replies
3
Boosts
0
Views
791
Activity
Aug ’23
How extract files in Assets.car?
I got a few answers from SO, but the tools are too old and they don't even run my macOS (12.6). Is there any official way to extract an Assets.car file? The reason I ask this question is that I want to re-use the icons for strings/storyboard files in Xcode packaged Assets.car (if it's legal).
Replies
0
Boosts
0
Views
1k
Activity
Sep ’23
Is there any builtin Text Find Bar?
I have a NSTableView which shows a list of translated text items. I want to provide a Find Bar for user to filter through the items, like the one I have in Xcode. Of course I don't want so many features; I only want to let user enter some text.
Replies
2
Boosts
0
Views
621
Activity
Sep ’23
How to implement similar navigation bar like what we have in Xcode?
Can anyone give any clues about how the navigation bar is implemented like below?
Replies
0
Boosts
0
Views
454
Activity
Sep ’23
How expand first root node when NSOutlineView is done with loading
I want to expand the first only root node when NSOutlineView is finished loading all data. How to get notified in code (possibly by some delegate function)?
Replies
1
Boosts
0
Views
407
Activity
Sep ’23
Ensure value in a Dictionary
In many cases, I need to get the value from a dictionary given a key (usually a string). I have the following helper class: public class ObjectCache<T> { private var cache = [String: T]() subscript(name: String) -> T? { get { return cache[name] } set { cache[name] = newValue } } func get(_ name: String, with builder: () -> T?) -> T? { var obj = cache[name] if obj == nil { obj = builder() cache[name] = obj } return obj } } This saves much keyboard typing and avoid common errors of oversight. Like below: let serviceURL = self.urlCache.get(name) { return comp.url }! Now my question is - Does Swift provide some builtin functionality like this? I just hope I did not re-event the wheel.
Replies
1
Boosts
0
Views
375
Activity
Sep ’23
switch case and === operator
I have the following code: func numberOfRows(in tableView: NSTableView) -> Int { switch tableView { case self.stringsTable: return self.stringsList?.count ?? 0 case self.localeTable: return self.localeMap.count default: print("numberOfRows not handled for \(tableView)") return 0 } } I wonder if there is any (performance) difference between case and ==== operator like below: func numberOfRows(in tableView: NSTableView) -> Int { if tableView === self.stringsTable { } // ... }
Replies
3
Boosts
0
Views
490
Activity
Sep ’23
Get row index when user click a button in NSTableCellView
I have a checkbox button in a table column (of course in a NSTableCellView). @IBAction func check_click(_ sender: Any) { // How do I know in which row this event occurred? // Once I get the row index I get the associated data item so that I can update the checked state. }
Replies
2
Boosts
0
Views
561
Activity
Sep ’23
Extension method for Optional of String
I came across an article about extension of Optional (https://useyourloaf.com/blog/empty-strings-in-swift/), but I cannot get it to work for the Optional extension. extension Optional where Wrapped == String { var isBlank: Bool { return self?.isBlank ?? true } } func testIsBlank() { for s in [nil, "", " ", "\t", "abc"] { print(s?.isBlank) } } For nil value, the output is still nil. I see the article is quite old dated back in 2019. There must be some changes in the language specs. What's going on here?
Replies
1
Boosts
0
Views
685
Activity
Sep ’23
Symbol navigator is polluted with thousands of system classes!
I have a test app. I added some extension classes to one of source code like below: extension String { func addPathComponent(_ path: String) -> String { return (self as NSString).appendingPathComponent(path) } func sameText(with: String) -> Bool { return self.caseInsensitiveCompare(with) == .orderedSame } var isBlank: Bool { allSatisfy { $0.isWhitespace } } } extension Optional where Wrapped == String { var isBlank: Bool { self?.isBlank ?? true } } Now the symbol navigator is polluted with many system classes: BTW, I am using Xcode 14.3.1.
Replies
1
Boosts
0
Views
628
Activity
Sep ’23
Any way to get array by reference?
Today I spent one hour to get myself educated on Array type. I have the following class in one of my app: class PathNode: Hashable, Comparable, CustomStringConvertible { var name: String! var path: String! var children: [PathNode]? static func == (lhs: PathNode, rhs: PathNode) -> Bool { lhs.name == rhs.name } static func < (lhs: PathNode, rhs: PathNode) -> Bool { lhs.name < rhs.name } func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(children) } /// Sort child nodes. func sort() { if let children = self.children { children.sort() for child in children { child.sort() } } } // other members... } The problem is in the sort function. I found out in my outline view the result is not sorted even though I did call sort on the root node. After about one hour's frustration, I came to realize that I forgot one import fact about the array type in Swift - it's a value type! I have to adjust sort function to the following code: /// Sort child nodes. func sort() { if self.children != nil { self.children!.sort() for child in self.children! { child.sort() } } } That's not an elegant way of writing code! Is there any other way to get a 'reference' to an array in Swift?
Replies
2
Boosts
0
Views
429
Activity
Sep ’23