我有一個裸骨架結構。Swift字符串沒有被存儲在結構中
struct Transaction {
var value: String = ""
var date: String = ""
var title: String = ""
}
在我的項目,Transaction
使用這樣的...
var transaction:Transaction = Transaction()
//loops 3 times
repeat {
let parsed = stringAndType(from:myParser)//-> (string:String, type:UInt8)
switch parsed.type {
case 1:
print("1 -- \(parsed.string")
transaction.value = parsed.string
case 2:
print("2 -- \(parsed.string)")
transaction.date = parsed.string
case 4:
print("4 -- \(parsed.string)")
transaction.title = parsed.string
default: break
}
} while myParser.isOk
print("Returning transaction: \(transaction)")
return transaction
在這段代碼中,創建了一個結構。解析器將數據提供給交換機,交換機將解析後的字符串分配給適當的變量Transaction
。當我運行下面的代碼時,輸出表明對transaction.date
和transaction.value
的分配不是粘連的。
輸出:
2 -- 12/22/2015
1 -- -5.00
4 -- RECURRING PAYMENT BACKBLAZE
Returning transaction: Transaction(value: "", date: "", title: "RECURRING PAYMENT BACKBLAZE")
有一個在stringAndType()
幕後複雜的緩衝。把它看作是一個C程序員,我真的很想認爲這個功能可能是問題所在。然而,我的印象是,Swift字符串是結構體,因此在寫入時被複制,就像整數或雙精度一樣。希望你能提供見解。感謝您的時間。
更新17年2月15日
按預期在此代碼的邏輯功能。我認爲這裏的問題是內存管理。爲了幫助推動了這一點,我已經......
- 刪除從我的開關
- 新增
didSet {}
給每個變量的print
線Transaction
是這樣的...
struct Transaction {
var value: String = "" {
didSet {
print("The VALUE has changed from \(oldValue) to \(value)")
}
}
//this is repeated appropriately for the other two variables
}
給定的輸出排除了任何邏輯問題。輸出:
The DATE has changed from to 12/22/2015
The VALUE has changed from to -5.00
The TITLE has changed from to RECURRING PAYMENT BACKBLAZE
Returning transaction: Transaction(value: "", date: "", title: "RECURRING PAYMENT BACKBLAZE")
stringAndType()
確實從一個不安全的緩衝器,讀但它拷貝字節到Data
結構,並返回從所複製的數據初始化的字符串。我認爲這將使我免於安全問題...也許是我的遺漏String
的實現細節?
我相信它正在進入開關櫃,並正在分配標題的最後一種情況,而不是'value'和'date'。 – ebby94
爲什麼你認爲,你切換案件將通過案例1?看起來它從不執行其他情況。 – JuicyFruit
當我嘗試使用具有字符串值的數組運行代碼時,一切正常:返回事務:事務(值:「2015年12月22日」,日期:「-5.00」,標題:「RECURRING PAYMENT BACKBLAZE」) – unkgd