Post

Replies

Boosts

Views

Activity

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
328
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
761
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
980
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
364
Sep ’23
Need help on Array and API design
I am working on an app which I plan to submit to App Store in 2 weeks. Now I have a headache with Array type. I have the following API design in my app: class SomeParser { func getTranslations(_ locale: String) -> [TranslationUnit]? { // Check if the locale units are already in a cache, if not build a new list // and return the list } } class MainVC { func doTranslation() { var list = parser.getTranslation("en") // Modify some units in the list. // How to put it back to cache? } } Now the problem is that since Array is a value type, the modified list is isolated. The only way to reflect the changes into cache is put the modified list back to cache: translationCache[locale] = modifiedList But this is counter-intuitive and waste of performance. Is there anyway to workaround this problem?
1
0
400
Oct ’23
Need help on generics where clause
I have the following class: /// Act as a reference container for value types. public class ValueBox<ValueType: ??> { public var value: ValueType public init() { value = ValueType() // Compiler error } public init(_ value: ValueType) { self.value = value } } Is it possible to specify the generic type ValueType can be inited?
1
0
298
Oct ’23
PropertyListDecoder and .strings file
I have the following code: let file = "/path/to/en.lproj/Localizable.strings" let dec = PropertyListDecoder() var f: PropertyListSerialization.PropertyListFormat = .openStep do { //let data = strings.data(using: .utf8)! let data = try Data(contentsOf: URL(fileURLWithPath: file)) let list = try dec.decode([String: String].self, from: data, format: &f) print("foramt:", f.rawValue) list.forEach { print($0.key, $0.value) } } catch { print(error) } It seems PropertyListDecoder can correctly decode .strings file format; detected format is openStep (value is 1). But I am note sure because I couldn't find any docs on PropertyListDecoder about .strings file. Can anyone confirm this?
1
0
435
Oct ’23
Is it safe to call low level Darwin function on FileHandle?
I have the following code: extension FileHandle { func readInto(_ buffer: inout [UInt8]) -> Int { buffer.withUnsafeMutableBytes { Darwin.read(fileDescriptor, $0.baseAddress, $0.count) } } } It can compile, but I wonder if this is supported since it's code in an app that is going to be submitted to App Store. The reason I don't use read(upToCount:) or readData(ofLength:) is that I am reading possibly very large files by small chunks and don't want to let Swift runtime allocate small buffers repeatedly.
0
0
307
Nov ’23
How read image file metadata?
I want to read metadata of image files such as copyright, author etc. I did a web search and the closest thing is CGImageSourceCopyPropertiesAtIndex: - (void)tableViewSelectionDidChange:(NSNotification *)notif { NSDictionary* metadata = [[NSDictionary alloc] init]; //get selected item NSString* rowData = [fileList objectAtIndex:[tblFileList selectedRow]]; //set path to file selected NSString* filePath = [NSString stringWithFormat:@"%@/%@", objPath, rowData]; //declare a file manager NSFileManager* fileManager = [[NSFileManager alloc] init]; //check to see if the file exists if ([fileManager fileExistsAtPath:filePath] == YES) { //escape all the garbage in the string NSString *percentEscapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)filePath, NULL, NULL, kCFStringEncodingUTF8); //convert path to NSURL NSURL* filePathURL = [[NSURL alloc] initFileURLWithPath:percentEscapedString]; NSError* error; NSLog(@"%@", [filePathURL checkResourceIsReachableAndReturnError:error]); //declare a cg source reference CGImageSourceRef sourceRef; //set the cg source references to the image by passign its url path sourceRef = CGImageSourceCreateWithURL((CFURLRef)filePathURL, NULL); //set a dictionary with the image metadata from the source reference metadata = (NSDictionary *)CGImageSourceCopyPropertiesAtIndex(sourceRef,0,NULL); NSLog(@"%@", metadata); [filePathURL release]; } else { [self showAlert:@"I cannot find this file."]; } [fileManager release]; } Is there any better or easy approach than this?
1
0
945
Dec ’23