A simple question, but I am not able to find the answer myself.
Note - I tried ProcessInfo.environment but it does not include system env vars.
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I am trying to encode/decode JSON data, and I have the following code:
struct SomeOrdinaryClass: Decodable {
// ...
}
struct SomeBox<T>: Decodable {
var data: T?
}
But Xcode gives me the following error:
myfile.swift:16:8 Type 'SomeBox' does not conform to protocol 'Decodable'
Is there anyway to overcome this?
I have a need to wrap several kinds of objects into a dictionary say [String: Any?], but how do I tell that the Any? object is all Encodable?
let params: [String: Any?] = ["num": 123, "text": "abc", "obj": encodableobject]
JSONEncoder().encode(params) // compiler error because Any? is not Encodable
The following code compiles fine in a normal Swift app, but not in the accompanying unit test bundle.
I don't have any idea why.
import Foundation
struct Dummy: NSObject { // Error: Inheritance from non-protocol type 'NSObject'
var name: String?
}
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?
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)?
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 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?
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.
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 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()
}
}
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?
// The builtin encoding does not support GBK/GB2312
String(data: data, encoding: .GBK)
How do I convert data which is encoded in GBK/GB2312 (or anything else) to a string instance?
I cannot get any clue on the differences between these 2 functions of Array type.
Can anyone explain by examples?