如果字符串在Swift中传递了逻辑语句,我怎么能连接它?

时间:2014-09-20 01:59:35

标签: random swift switch-statement string-concatenation

我的挑战是双重的:

  1. 从类似字符串数组中选择单个字符串,但仅限于首先传递布尔测试。

  2. "最后"我需要将生成的任何/所有字符串连接成一个完整的文本,整个代码必须在Swift中。

  3. 插图:信封代码的背面,用于说明逻辑:

        generatedText.text =
    
        case Int1 <= 50 && Int2 == 50
            return generatedParagraph1 = pick one string at RANDOM from a an array1 of strings
    
        case Int3 =< 100
            return generatedParagraph2 = pick one string at RANDOM from a an array2 of strings
    
        case Int4 == 100
            return generatedParagraph3 = pick one string at RANDOM from a an array3 of strings
    
        ...etc
    
        default
            return "Nothing to report"
    
    and concatenate the individual generatedParagraphs
    

    尝试:代码在stringArray1,2和3中选择一个随机元素。 代码返回的示例:

    ---&GT; &#34; Sentence1_c.Sentence2_a.Sentence3_b&#34;

    问题:我需要代码只在第一次传递布尔值时选择一个元素。这意味着最终的连接字符串(concastString)可以为空,只包含一个或多个元素,具体取决于有多少bool为True。有谁知道怎么做?

    import Foundation
    
    var stringArray1 = ["","Sentence1_a.", "Sentence1_b.", "Sentence1_c."]
    var stringArray2 = ["","Sentence2_a.", "Sentence2_b.", "Sentence2_c."]
    var stringArray3 = ["","Sentence3_a.", "Sentence3_b.", "Sentence3_c."]
    
    
    let count1 = UInt32(stringArray1.count)-1
    let count2 = UInt32(stringArray2.count)-1
    let count3 = UInt32(stringArray3.count)-1
    
    var randomNumberOne = Int(arc4random_uniform(count1))+1
    var randomNumberTwo = Int(arc4random_uniform(count2))+1
    var randomNumberThree = Int(arc4random_uniform(count3))+1
    
    let concatString = stringArray1[randomNumberOne] + stringArray2[randomNumberTwo] + stringArray3[randomNumberThree]
    

1 个答案:

答案 0 :(得分:0)

好吧,我没有通过Bool,但是我显示了来自[String]的连续三个随机字符串。我在操场上跑了这个。

import Foundation

var stringArray = [String]()

for var i = 0; i < 100; i++ {
    stringArray.append("text" + "\(i)")
}


func concat (array: [String]) -> String {
    let count = UInt32(stringArray.count)
    let randomNumberOne = Int(arc4random_uniform(count))
    let randomNumberTwo = Int(arc4random_uniform(count))
    let randomNumberThree = Int(arc4random_uniform(count))

    let concatString = array[randomNumberOne] + array[randomNumberTwo] + array[randomNumberThree]

    return concatString
}

let finalString = concat(stringArray)