gpt4 book ai didi

没有 "Optional"的 Swift 字符串/字符可选打印

转载 作者:搜寻专家 更新时间:2023-11-01 05:43:44 25 4
gpt4 key购买 nike

swift 的新手,并尝试打印带有字符串插值的 Optional。我希望它在 Optional 为空时打印 nil,但也希望它在实际包含字符串/字符时正确打印字符串/字符。

所以我想要完成的应该可以在这里使用:

print("The result is: \(funcToReturnOptional)")

结果是有值的结果或被打印的nil

我该怎么做?我不想强制解包,因为我希望对实际函数进行一些测试以返回 nil。

为了记录,函数是:

func firstNonRepeatingChar(input:String)->Character?{
//set a default return object
var result: Character? = nil
//convert input for easy and clean navigation
let converted = Array(input)
//set start of enumeration
var index: Int = 0
//set variable to compare
var c:Character
//should only trigger if non-empty input
while index<converted.count-1{
c=converted[index]
//check for non-repeated value
if !converted[index+1..<converted.count].contains(c){
result=c
return result
}
index+=1
}
return result
}

我正在尝试像这样打印:

print(firstString+" should return \(firstNonRepeatingCharacter(input: firstString)??"nil")")

最佳答案

这是函数:

func firstNonRepeatingChar(input:String)->Character?{
//set a default return object
var result: Character? = nil
//convert input for easy and clean navigation
// let converted = Array(input) swift2
let converted = [Character](input.characters) //swift3
//set start of enumeration
var index: Int = 0
//set variable to compare
var c:Character
//should only trigger if non-empty input
while index<converted.count-1{
c=converted[index]
//check for non-repeated value
if !converted[index+1..<converted.count].contains(c){
result=c
return result
}
index+=1
}
return result
}

并调用:

print("The result is: \(firstNonRepeatingChar(input: "I miss you")?.description ?? "nil")")

输出控制台:

The result is: I

 let fistString = "I miss you"  
print("here is FistString: \(fistString) and The result is: \(firstNonRepeatingChar(input: fistString)?.description ?? "nil")")

关于没有 "Optional"的 Swift 字符串/字符可选打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46980459/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com