计算用户填充的字符串中的单词

时间:2016-12-02 16:16:45

标签: ios swift

正如标题所说,我想计算字符串中的单词,由用户填写。为此,我将简化它一点,我将计算字符串中的空格,将值存储在另一个变量中并打印新变量。

我使用的代码如下:

import UIKit

class TransViewController: UIViewController {

@IBOutlet var trad_text: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    trad_text!.layer.borderWidth = 1
    trad_text!.layer.cornerRadius = 20
    trad_text!.layer.borderColor = UIColor(red:0.22, green:0.26, blue:0.39, alpha:1.0).cgColor
}



override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    let text = trad_text.text

    let num_words = text?.characters.split(separator: " ").map(String.init)
    print(num_words)
    // Dispose of any resources that can be recreated.
}

但它不会打印任何数量的单词。有人能找到为什么这段代码会出错吗?

感谢您的时间

1 个答案:

答案 0 :(得分:0)

我最终使用以下代码完成了它,也许对某人有用:

import UIKit
import Foundation

class TransViewController: UIViewController {

final class Shared {
    static let shared = Shared() //lazy init, and it only runs once

    var stringValue : String!
    var num_words : Int!
    var boolValue   : Bool!
}

@IBOutlet var trad_text: UITextView!
@IBOutlet var buttonTrad: UIButton!
@IBOutlet var labelsitoh: UILabel!

@IBAction func butCalc(_ sender: AnyObject) {

    let text = trad_text.text

    let num_words =  (text?.components(separatedBy: " ").count)!-1

    Shared.shared.num_words = num_words
}

override func viewDidLoad() {
    super.viewDidLoad()

    trad_text!.layer.borderWidth = 1
    trad_text!.layer.cornerRadius = 20
    trad_text!.layer.borderColor = UIColor(red:0.22, green:0.26, blue:0.39, alpha:1.0).cgColor
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

    // Dispose of any resources that can be recreated.
}