Post

Replies

Boosts

Views

Activity

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
639
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
609
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
402
Sep ’23
Weird error with HTTPS connection
I have a weird problem with HTTPS connection. Task <A19A5441-F5CD-4F8C-8C88-73FC679D8AE0>.<1> finished with error [-1200] Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." I am trying to bypass server certificate of my website because it's self-signed. The following code works in a test app, but not in another app. They have exactly have the same entitlements: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>com.apple.security.app-sandbox</key> <true/> <key>com.apple.security.files.user-selected.read-write</key> <true/> <key>com.apple.security.network.client</key> <true/> </dict> </plist> func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { let protectionSpace = challenge.protectionSpace guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust, protectionSpace.host.contains("mywebsite.net") else { completionHandler(.performDefaultHandling, nil) return } guard let serverTrust = protectionSpace.serverTrust else { completionHandler(.performDefaultHandling, nil) return } let credential = URLCredential(trust: serverTrust) completionHandler(.useCredential, credential) } @IBAction func testMenuItem_select(_ sender: Any) { print("\(sender)") Preferences.instance.openTipShowed = false testURLSession() func testURLSession() { let session = URLSession(configuration: URLSessionConfiguration.ephemeral, delegate: self, delegateQueue: nil) let url2 = "https://www.mywebsite.net/spiders.txt" let url3 = "https://www.apple.com/" let url = URL(string: url2)! var request = URLRequest(url: url) let task = session.dataTask(with: request) { data, response, error in if let error { print(error) } if let data { let text = String(data: data, encoding: .utf8) print("HTTP response object:", response ?? "") print("HTTP resonse text:", text ?? "<empty response>") } } task.resume() } }
1
0
694
Oct ’23
FileMerge won't run on macOS 12.7
I am still on Xcode 14.3 and my macOS is version 12.7 (21G816). Today I am surprised to find out that FileMerge tool won't run when I invoke it from Xcode "Open Developer Tool" menu. Is there a standalone download for this tool? Or is there any better alternatives to it?
2
0
735
Oct ’23
Data(contentsOf:) with huge file
I have a function that computes MD5 hash of a file: func ComputeMD5(ofFile path: String) -&gt; [UInt8]? { if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { var digest = [UInt8](repeating: 0, count: 16) data.withUnsafeBytes { _ = CC_MD5($0.baseAddress, UInt32(data.count), &amp;digest) } return digest } return nil } Now I wonder/worry what happens if the file is very huge. Does the runtime perform disk memory paging?
2
1
667
Nov ’23
What should I do with UTI (NSImage.imageTypes)?
Per the docs, NSImage.imageTypes returns a list UTI's, something like below: com.adobe.pdf com.apple.pict com.adobe.encapsulated-postscript public.jpeg public.png com.compuserve.gif com.canon.tif-raw-image ... What I need is get file extensions of a UTI. For example, public.jpeg picture file may have several file extensions, say .jpg,.jpeg,.jfif. Does Cocoa provide any API to query for this information?
2
0
911
Dec ’23