I cannot get any clue on the differences between these 2 functions of Array type.
Can anyone explain by examples?
Post
Replies
Boosts
Views
Activity
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 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 a function that computes MD5 hash of a file:
func ComputeMD5(ofFile path: String) -> [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), &digest)
}
return digest
}
return nil
}
Now I wonder/worry what happens if the file is very huge. Does the runtime perform disk memory paging?
// 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 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 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?
In other languages, I am able to get current function's name using some kind of so-called reflection API. Does Swift provide similar API?
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 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 am having coding design difficulties with Array in Swift, see this post. So I decided to turn to the old NSMutableArray.
I'd like to know if there are any known problems of this approach. Any pitfalls and known practices?
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?
Suppose I have the following class:
class Some {
var list = [String]()
}
// In other places, I want to append to the list
someInstance.list.append("new string")
// ...but I do not want to re-assign the list itself:
someInstance.list = [String]()
What is the exact syntax for declaring list?
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?
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.