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?
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
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'
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).
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)?
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.
Can anyone give any clues about how the navigation bar is implemented like below?
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.
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?
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?
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?
I have a need to list all known audio/image file types in a planned app.
What I have known so far:
images
.apng
.avi, .avif
.gif
.jpg, .jpeg, .jfif, .pjpeg, .pjp
.png
.svg
.webp
audio
.aif
.cda
.mid, .midi
.mp3
.mpa
.ogg
.wav
.wma
What are the missing ones?
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.
I want to convert byte size strings like "1234kb", "100mb" or "5gb" to their actual number representation. Is there any builtin functions for this purpose?
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?
Does Swift support this? Til now my understanding is that reflection only works with public members. Is it possible to get private/static members of a type?