swift新手,并尝试使用字符串插值打印Optional
。我希望它在nil
为空时打印Optional
,但也希望它在实际包含字符串/字符时正确打印它。
所以我想要完成的工作应该可以在这里使用:
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")")
答案 0 :(得分:0)
这是功能:
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")")
输出控制台:
结果是:我
或
let fistString = "I miss you"
print("here is FistString: \(fistString) and The result is: \(firstNonRepeatingChar(input: fistString)?.description ?? "nil")")
答案 1 :(得分:-1)
Swift 4
将字符可选或展开为字符串nil
let result = firstNonRepeatingCharacter(input: firstString)?.description ?? "nil"
print("\(firstString) should return \(result)")