我正在尝试在Swift 3的文本字段中输出结果,但是当按下按钮时没有任何反应,甚至都没有在控制台中打印。它应该是我猜的最后3行代码中的某个地方。我无法弄清楚我做错了什么,所以非常感谢你的帮助!我也是Swift的新手,所以对你来说这可能是显而易见的,但对我来说却是死路一条。
这是我的代码:
@IBAction func encrypt(sender: AnyObject?) {
let text = encryptText.text
let key = pkey.text
func encrypt(text: String) -> (text: String, key: [Int]) {
let text = text.lowercased()
let key = self.key(count: text.characters.count)
let map = self.map()
var output = String()
for (index, character) in text.characters.enumerated() {
if character == " " {
output.append(character)
}
else {
if let letterIndex = map.forward[String(character)] {
let keyIndex = key[index]
let outputIndex = (letterIndex + keyIndex + map.lastCharacterIndex) % map.lastCharacterIndex
if let outputCharacter = map.reversed[outputIndex] {
output.append(outputCharacter)
}
}
}
}
print(text)
outputText.text = output
return (text: output.uppercased(), key: key)
}
}
答案 0 :(得分:1)
你有一个函数(encrypt
)嵌套在另一个函数中(@IBAction
也称为encrypt
),但你永远不会调用嵌套函数。尝试这样的事情:
@IBAction func encrypt(sender: AnyObject?) {
func encrypt(text: String) -> (text: String, key: [Int]) {
let text = text.lowercased()
let key = self.key(count: text.characters.count)
let map = self.map()
var output = String()
for (index, character) in text.characters.enumerated() {
if character == " " {
output.append(character)
}
else {
if let letterIndex = map.forward[String(character)] {
let keyIndex = key[index]
let outputIndex = (letterIndex + keyIndex + map.lastCharacterIndex) % map.lastCharacterIndex
if let outputCharacter = map.reversed[outputIndex] {
output.append(outputCharacter)
}
}
}
}
return (text: output.uppercased(), key: key)
}
let text = encryptText.text
let key = pkey.text
// call the encrypt function
let (resultText, resultKey) = encrypt(text: text)
// put the result in the text view
outputText.text = resultText
}
确切地确定你在做什么也有点困难,因为你声明了许多具有相同名称的变量(文本,密钥,加密等)。选择这些名称的细微变化可以提高代码的可读性。