简体   繁体   English

如何快速转换nil字符串

[英]How to convert a nil string in swift

I try to filter just the name of my peripheral.name object. 我尝试仅过滤我的peripheral.name对象的名称。 Usually, that's no problem. 通常,这没问题。 For example: [Optional"Apple TV"] works like it should. 例如: [Optional"Apple TV"]工作原理与应有的一样。 But if I get a nil object, I get a fatal error and I don't understand why... 但是,如果我得到一个nil对象,就会出现致命错误,并且我不明白为什么...

let str = "\(peripheral.name)"
let test_str = str.substringWithRange(Range<String.Index>(start:str.startIndex.advancedBy(10), end: str.endIndex.advancedBy(-2)))   
print(test_str)

I thought that the operation "\\(peripheral.name)" converts every object into a string... also a nil type. 我认为操作"\\(peripheral.name)"会将每个对象转换为字符串...也是nil类型。

str will always be a String indeed: if peripheral.name is nil, it will result in an empty string. str的确确实始终是一个String:如果peripheral.name名为nil,它将导致一个空字符串。

But you're using advancedBy with hardcoded values like 10: it won't work on an empty string, that's the source of your fatal error, you can't move along an index that doesn't exist. 但是,您正在将advancedBy与硬编码的值(例如10)一起使用:它将不适用于空字符串,这是致命错误的根源,您无法沿着不存在的索引移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM