我有一个将字符类型转换为字符串类型的问题.首先,我在String的扩展名下面用于在String中查找第n个字符.
extension String {
func characterAtIndex(index: Int) -> Character? {
var cur = 0
for char in self {
if cur == index {
return char
}
cur++
}
return nil
}
}
Run Code Online (Sandbox Code Playgroud)
我得到了这个类扩展我想要的东西.但是,当我将第n个字符用于我的自定义UIButton的标题时,会出错.我的Uibutton课程是
class hareketliHarfler: UIButton {
init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
}
func getLetter(letter:String!){
self.titleLabel.text = letter
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试访问"getLetter(letter:String)"函数时出现错误.以下是主视图控制器代码的示例:
var harfim = hareketliHarfler(frame: CGRectMake(100,100,100,100))
var str="This is my String"
var bufi=str.characterAtIndex(3)
harfim.getLetter(bufi as AnyObject) ****
Run Code Online (Sandbox Code Playgroud)
在*部分我尝试.getLetter(bufi),. getLetter(bufi as String)我也尝试更改函数的参数类型.看起来像:func getLetter(letter:Character!)或func getLetter(letter:AnyObject!)......等找不到方法.需要帮助.谢谢
var numbers = "Hello,Goodbye,Hi,Bye"
var numbersArr = numbers.componentsSeparatedByString(",")
Run Code Online (Sandbox Code Playgroud)
//["Hello"."Goodbye","Hi","Bye"]
以上是我正在尝试做的基本表示.我正在尝试使用componentsSeparatedByString()逗号将字符串拆分为数组,其中数组的每个组件都位于原始字符串的每个逗号之间.
我正在使用IBM Swift Sandbox(抱歉,我在Windows上:)),在Swift 3.0中,我收到此错误消息:
value of type 'String' has no member 'componentsSeparatedByString'
Run Code Online (Sandbox Code Playgroud)
我知道Swift 3相当新,这就是为什么我找不到这个错误的任何其他参考.
在Swift 1.2的最新升级之后,我无法弄清楚如何将一行文本拆分成单词.我曾经这样做过:
let bits = split(value!, { $0 == " "}, maxSplit: Int.max, allowEmptySlices: false)
Run Code Online (Sandbox Code Playgroud)
但那不再有效,因为......
Cannot invoke 'split' with an argument list of type '(String, (_) -> _, maxSplit: Int, allowEmptySlices: Bool)'
Run Code Online (Sandbox Code Playgroud)
嗯,好吧,即使我可以上次建造?好吧,我们试试......
let bits = split(value!, { $0 == " "})
Run Code Online (Sandbox Code Playgroud)
那个和我能想到的其他版本最终都说:
Missing argument for parameter 'isSeparator' in call
Run Code Online (Sandbox Code Playgroud)
让我们听听它测试新的编程语言!好极了!
谁知道1.2的正确秘诀?
在Swift 4中,.split(separator:)apple在String struct中引入了新方法.所以要用一个更快的空格来分割一个字符串,例如.
let str = "My name is Sudhir"
str.components(separatedBy: " ")
//or
str.split(separator: " ")
Run Code Online (Sandbox Code Playgroud) 我要这个:
var String1 = "Stack Over Flow"
var desiredOutPut = "SOF" // the first Character of each word in a single String (after space)
Run Code Online (Sandbox Code Playgroud)
我知道如何从字符串中获取第一个字符,但不知道该怎么做这个问题.