2015-09-25 99 views
2

我正在向UIWebView添加一些HTML內容。Swift向UIWebView添加HTML,表達式太複雜了

這條線:

generatedHtml += "<br><p style=\"font-family:'Chevin-Medium';font-size:12px;color:#505050;padding-top:0px;\">" + newsItem.entry.likes + " like this " + newsItem.entry.comments?.count + " comments</p>" 

我得到:

expressions was too complex to be solved in reasonable time 

我只是在做一個計數陣列上,我不知道如何作出這樣的那麼複雜?

物體看起來是這樣的:

public class NewsItem: NSObject { 
    var entry: EntryObject = EntryObject() 

} 

public class EntryObject: NSObject { 
    var comments: [Comment]? = [] 
} 

回答

2

newsItem.entry.comments?.count是一個整數,你可以不爲整數添加到使用+一個字符串,你應該使用\()字符串插值:

" like this \(newsItem.entry.comments?.count) comments</p>" 

或者使用String初始值設定項如果您需要繼續使用+

" like this " + String(newsItem.entry.comments?.count) + " comments</p>" 

如果錯誤「太複雜」仍然存在,則必須分解語句並使用變量,而不是直接插入表達式。

1

嘗試通過這種方式

var countComments : Int = 0 

//Validate comment counting 
if let cComments = newsItem.entry.comments?.count 
{ 
    countComments = cComments 
} 

//... Some code here ... 

//Devide to Conquest. 
//If is easy to find... Is not hard to fix 
generatedHtml += "<br>" 
generatedHtml += "<p style=\"font-family:'Chevin-Medium';font-size:12px;color:#505050;padding-top:0px;\">" 
generatedHtml += "\(newsItem.entry.likes) " 
generatedHtml += "like this \(countComments) comments" //Here you have a valid value 
genetatedHtml += "</p>" 

但是,爲什麼呢?

也許你有一個問題,可選值newsItem.entry.comments?.count,可以讓你一個零值。然後,首先驗證值並確定返回的內容。更好「0」,比

當你分割字符串創建一個有效的值,調試工作會更容易執行。您可以更好地瞭解發生錯誤的位置。

也許這不是對您的問題的確定解決方案,而是幫助您解決問題的好方法。

相關問題