xcode Swift 4 中 textField 的前 4 个字符的子字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45372653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
substring of the first 4 characters from a textField in Swift 4
提问by JamLis
I'm trying to create a substring of the first 4 characters entered in a textField in Swift 4 on my iOS app.
我正在尝试在我的 iOS 应用程序的 Swift 4 中的 textField 中创建前 4 个字符的子字符串。
Since the change to Swift 4 I'm struggling with basic String parsing.
自从更改为 Swift 4 以来,我一直在努力进行基本的字符串解析。
So based on Apple documentation I'm assuming I need to use the substring.index function and I understand the second parameter (offsetBy) is the number of characters to create a substring with. I'm just unsure how I tell Swift to start at the beginning of the string.
因此,根据 Apple 文档,我假设我需要使用 substring.index 函数,并且我知道第二个参数 (offsetBy) 是用于创建子字符串的字符数。我只是不确定如何告诉 Swift 从字符串的开头开始。
This is the code so far:
这是到目前为止的代码:
let postcode = textFieldPostcode.text
let newPostcode = postcode?.index(STARTATTHEBEGININGOFTHESTRING, offsetBy: 4)
I hope my explanation makes sense, happy to answer any questions on this.
我希望我的解释有意义,很高兴回答有关此的任何问题。
Thanks,
谢谢,
回答by vadian
In Swift 4 you can use
在 Swift 4 中你可以使用
let string = "Hello World"
let first4 = string.prefix(4) // Hell
The type of the result is a new type Substring
which behaves very similar to String
. However if first4
is supposed to leave the current scope – for example as a return value of a function – it's recommended to create a String
explicitly:
结果的类型是一种新类型Substring
,其行为与String
. 但是,如果first4
应该离开当前范围——例如作为函数的返回值——建议String
显式创建:
let first4 = String(string.prefix(4)) // Hell
See also SE 0163 String Revision 1
另请参阅SE 0163 字符串修订版 1
回答by Mohammad Sadegh Panadgoo
In Swift 4:
在 Swift 4 中:
let postcode = textFieldPostcode.text!
let index = postcode.index(postcode.startIndex, offsetBy: 4)
let newPostCode = String(postcode[..<index])