我正在编写一个应用程序来取一串字母并将它们分成3个字母组,然后基本上将这些组转换为mapping
的指定单词,我已经做到了这一点。但是现在,我需要从print()
命令到Label.text =
命令结束我的代码。
@IBOutlet weak var Label: UILabel!
@IBOutlet weak var textField: UITextField!
@IBAction func decBttn(_ sender: Any) {
var textField:String
let mapping = [
"aaa" :
"Lysine" ,
"aag" :
"Lysine" ,
"aac" :
"Asparagine" ,
// lots more here
]
let characters = textField.characters
var index = 0
while index < characters.count {
let start = textField.index(textField.startIndex, offsetBy: index)
var endOffset = index+3
if index+3 > characters.count {
endOffset = characters.count
}
let end = textField.index(textField.startIndex, offsetBy: endOffset)
let range = start..<end
let groupedSubstring = textField[range]
print(mapping [groupedSubstring] ?? groupedSubstring)
index = index + 3
这是我正在使用的代码,有什么想法吗?
答案 0 :(得分:0)
您可能希望目标视图为UITextView
,而不是标签。 UITextViews
默认为多行,并支持滚动。
使用这样的代码:
var output = ""
while index < characters.count {
let start = textField.index(textField.startIndex, offsetBy: index)
var endOffset = index+3
if index+3 > characters.count {
endOffset = characters.count
}
let end = textField.index(textField.startIndex, offsetBy: endOffset)
let range = start..<end
let groupedSubstring = textField[range]
output += mapping[groupedSubstring] ?? groupedSubstring + "\n"
index = index + 3
}
outputView.text = output
(重写为使用IBOutlet
的输出outputView
,因为该名称可用于您的问题中的输出UILabel,或UITextView(我的建议)
(请注意,您可以使用stride()
和map()
将上述内容重写为更简洁,但这可能超出您当前的技能水平,因此我不会去那里。)
使用函数式编程样式重写循环代码:
首先,创建一个String扩展:(这段代码应该在它自己的文件中,不应该在另一个对象的定义中。)
///String extension to add `chunkBy(_:)`
extension String {
/**
This function breaks a string into an array of chunks of size chunkSize (the last entry may be shorter)
- Parameters:
- chunkSize: The size of the chunks
- Returns: An array of strings
*/
func chunkBy(_ chunkSize: Int) -> [String] {
//Create an array of starting indexes for each output chunk
let indexes = stride(from: 0, to: input.count, by: chunkSize)
//Map the array of start index values into an array of substrings of chunkSize.
let result: [String] = indexes.map {
let startIndex = input.index(input.startIndex, offsetBy: $0)
let endIndex = input.index(input.startIndex, offsetBy: $0 + chunkSize, limitedBy: input.endIndex) ?? input.endIndex
let substring = input[startIndex..<endIndex]
return String(substring)
}
return result
}
}
现在这里是代码将进入视图控制器的字符串解析方法:
var input = "aaaaacaagxyza" //This is test data; You'd use user input.
let mapping = [
"aaa" :
"Lysine" ,
"aag" :
"Lysine" ,
"aac" :
"Asparagine" ,
// lots more here
]
let result = input.chunkBy(3)
.map { mapping[$0, default: $0] } //Map the array of chunks to dictionary lookups, or use the original if none found
//Use the reduce function to collapse the array of strings into one string with newlines.
.reduce ("",{ $0 + $1 + "\n" })
print (result)
//Now install your result into your text view.