我构建了一个从数据库中请求图像URL的webservis。而我想在迅速展示它。但是我在var photo line上发现了这个错误:
无法将'subSequence'类型的值(又名'String.CharacterView')转换为集合中的'String'类型
let requestResponse = self.sendToServer(postUrl: "localhost",data:"abc")
let Seperated = requestResponse.characters.split(separator: " ")
var photo = Seperated[0] as String
let imageURL = URL(string: photo)
if let imageData = try? Data(contentsOf: imageURL!) {
...
}
答案 0 :(得分:27)
考虑这样的事情:
let requestResponse = "some string"
let separated = requestResponse.characters.split(separator: " ")
if let some = separated.first {
let value = String(some)
// Output: "some"
}
答案 1 :(得分:2)
如果使用Swift 4,您将像这样使用
:let separated = requestResponse.split(separator: " ")
var photo = String(separated.first ?? "")
答案 2 :(得分:2)
split
返回Substring
的列表,因此我们必须将它们映射(转换)为String
。为此,您只需将Substring
传递给String
的{{1}}函数:
init
答案 3 :(得分:0)
一种通过使用高阶函数分割字符串来获取字符串的方法:
best_results = {}
seeds = [1, 3, 5, 7, 11, 13, 17, 19]
#find best hyperparameters c and gamma
for seed in seeds:
result = {'best_c' : 0.0, 'best_gamma' : 0.0, 'best_score' : 0.0 }
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.1, random_state=seed)
for C in np.linspace(10.0, 200, 40):
for gamma in np.linspace(0.001, 0.01, 20):
rbf_clf = svm.SVC(C = C, gamma = gamma)
scores = cross_val_score(rbf_clf, X_train, Y_train, cv=10, n_jobs=-1)
if(scores.mean() > result['best_score']):
result = {'best_c' : C, 'best_gamma' : gamma, 'best_score' : scores.mean() }
index = "%0.3f%0.3f"%(result['best_c'], result['best_gamma'])
if(not index in best_results):
best_results[index] = []
best_results[index].append(result)
best_index = ""
moda = 0
for index in best_results:
if(len(best_results[index]) > moda):
moda = len(best_results[index])
best_index = index
# get the accuracy of my model
best_c = best_results[best_index][0]['best_c']
best_gamma = best_results[best_index][0]['best_gamma']
test_scores = np.zeros(len(seeds))
for i in range(0,len(seeds)):
seed = seeds[i]
X_train, X_test, Y_train, Y_test = train_test_split(X, y, test_size=0.1, random_state=seed)
rbf_clf = svm.SVC(C = best_c, gamma = best_gamma)
rbf_clf.fit(X_train, Y_train)
test_scores[i] = rbf_clf.score(X_test, Y_test)
print("C:%0.3f\t Gamma:%0.5f\t Accuracy:%0.5f" %(best_c, best_gamma, test_scores.mean()))
答案 4 :(得分:0)
最简单的解决方案。
let Seperated = requestResponse.characters.split(separator: " ").map { String($0) }