repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
winkelsdorf/SwiftWebViewProgress | refs/heads/master | SwiftWebViewProgress/SwiftWebViewProgress/SwiftWebViewProgress.swift | mit | 1 | //
// SwiftWebViewProgress.swift
// SwiftWebViewProgress
//
// Created by Daichi Ichihara on 2014/12/03.
// Copyright (c) 2014 MokuMokuCloud. All rights reserved.
//
import UIKit
protocol WebViewProgressDelegate {
func webViewProgress(webViewProgress: WebViewProgress, updateProgress progress: Float)
}
class WebViewProgress: NSObject, UIWebViewDelegate {
var progressDelegate: WebViewProgressDelegate?
var webViewProxyDelegate: UIWebViewDelegate?
var progress: Float = 0.0
private var loadingCount: Int!
private var maxLoadCount: Int!
private var currentUrl: NSURL?
private var interactive: Bool!
private let InitialProgressValue: Float = 0.1
private let InteractiveProgressValue: Float = 0.5
private let FinalProgressValue: Float = 0.9
private let completePRCURLPath = "/webviewprogressproxy/complete"
// MARK: Initializer
override init() {
super.init()
maxLoadCount = 0
loadingCount = 0
interactive = false
}
// MARK: Private Method
private func startProgress() {
if progress < InitialProgressValue {
setProgress(InitialProgressValue)
}
}
private func incrementProgress() {
var progress = self.progress
var maxProgress = interactive == true ? FinalProgressValue : InteractiveProgressValue
let remainPercent = Float(loadingCount / maxLoadCount)
let increment = (maxProgress - progress) / remainPercent
progress += increment
progress = fmin(progress, maxProgress)
setProgress(progress)
}
private func completeProgress() {
setProgress(1.0)
}
private func setProgress(progress: Float) {
if progress > self.progress || progress == 0 {
self.progress = progress
progressDelegate?.webViewProgress(self, updateProgress: progress)
}
}
// MARK: Public Method
func reset() {
maxLoadCount = 0
loadingCount = 0
interactive = false
setProgress(0.0)
}
// MARK: - UIWebViewDelegate
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.URL!.path == completePRCURLPath {
completeProgress()
return false
}
var ret = true
if webViewProxyDelegate!.respondsToSelector("webView:shouldStartLoadWithRequest:navigationType:") {
ret = webViewProxyDelegate!.webView!(webView, shouldStartLoadWithRequest: request, navigationType: navigationType)
}
var isFragmentJump = false
if let fragmentURL = request.URL?.fragment {
let nonFragmentURL = request.URL?.absoluteString?.stringByReplacingOccurrencesOfString("#"+fragmentURL, withString: "")
isFragmentJump = nonFragmentURL == webView.request!.URL?.absoluteString
}
var isTopLevelNavigation = request.mainDocumentURL! == request.URL
var isHTTP = request.URL?.scheme == "http" || request.URL?.scheme == "https"
if ret && !isFragmentJump && isHTTP && isTopLevelNavigation {
currentUrl = request.URL
reset()
}
return ret
}
func webViewDidStartLoad(webView: UIWebView) {
if webViewProxyDelegate!.respondsToSelector("webViewDidStartLoad:") {
webViewProxyDelegate!.webViewDidStartLoad!(webView)
}
loadingCount = loadingCount + 1
maxLoadCount = Int(fmax(Double(maxLoadCount), Double(loadingCount)))
startProgress()
}
func webViewDidFinishLoad(webView: UIWebView) {
if webViewProxyDelegate!.respondsToSelector("webViewDidFinishLoad:") {
webViewProxyDelegate!.webViewDidFinishLoad!(webView)
}
loadingCount = loadingCount - 1
// incrementProgress()
let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState")
var interactive = readyState == "interactive"
if interactive {
self.interactive = true
let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);"
webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS)
}
var isNotRedirect: Bool
if let _currentUrl = currentUrl {
if _currentUrl == webView.request?.mainDocumentURL {
isNotRedirect = true
} else {
isNotRedirect = false
}
} else {
isNotRedirect = false
}
var complete = readyState == "complete"
if complete && isNotRedirect {
completeProgress()
}
}
func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
if webViewProxyDelegate!.respondsToSelector("webView:didFailLoadWithError:") {
webViewProxyDelegate!.webView!(webView, didFailLoadWithError: error)
}
loadingCount = loadingCount - 1
// incrementProgress()
let readyState = webView.stringByEvaluatingJavaScriptFromString("document.readyState")
var interactive = readyState == "interactive"
if interactive {
self.interactive = true
let waitForCompleteJS = "window.addEventListener('load',function() { var iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.src = '\(webView.request?.mainDocumentURL?.scheme)://\(webView.request?.mainDocumentURL?.host)\(completePRCURLPath)'; document.body.appendChild(iframe); }, false);"
webView.stringByEvaluatingJavaScriptFromString(waitForCompleteJS)
}
var isNotRedirect: Bool
if let _currentUrl = currentUrl {
if _currentUrl == webView.request?.mainDocumentURL {
isNotRedirect = true
} else {
isNotRedirect = false
}
} else {
isNotRedirect = false
}
var complete = readyState == "complete"
if complete && isNotRedirect {
completeProgress()
}
}
}
| 9df329aceef447509dbe206f04cde179 | 35.366667 | 331 | 0.615076 | false | false | false | false |
Sajjon/Zeus | refs/heads/master | Pods/Alamofire/Source/TaskDelegate.swift | apache-2.0 | 2 | //
// Error.swift
//
// Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/// The task delegate is responsible for handling all delegate callbacks for the underlying task as well as
/// executing all operations attached to the serial operation queue upon task completion.
open class TaskDelegate: NSObject {
// MARK: Properties
/// The serial operation queue used to execute all operations after the task completes.
open let queue: OperationQueue
var task: URLSessionTask
let progress: Progress
var data: Data? { return nil }
var error: NSError?
var initialResponseTime: CFAbsoluteTime?
var credential: URLCredential?
// MARK: Lifecycle
init(task: URLSessionTask) {
self.task = task
self.progress = Progress(totalUnitCount: 0)
self.queue = {
let operationQueue = OperationQueue()
operationQueue.maxConcurrentOperationCount = 1
operationQueue.isSuspended = true
operationQueue.qualityOfService = .utility
return operationQueue
}()
}
// MARK: NSURLSessionTaskDelegate
var taskWillPerformHTTPRedirection: ((URLSession, URLSessionTask, HTTPURLResponse, URLRequest) -> URLRequest?)?
var taskDidReceiveChallenge: ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?))?
var taskNeedNewBodyStream: ((URLSession, URLSessionTask) -> InputStream?)?
var taskDidCompleteWithError: ((URLSession, URLSessionTask, NSError?) -> Void)?
@objc(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void)
{
var redirectRequest: URLRequest? = request
if let taskWillPerformHTTPRedirection = taskWillPerformHTTPRedirection {
redirectRequest = taskWillPerformHTTPRedirection(session, task, response, request)
}
completionHandler(redirectRequest)
}
@objc(URLSession:task:didReceiveChallenge:completionHandler:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
{
var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling
var credential: URLCredential?
if let taskDidReceiveChallenge = taskDidReceiveChallenge {
(disposition, credential) = taskDidReceiveChallenge(session, task, challenge)
} else if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let host = challenge.protectionSpace.host
if let serverTrustPolicy = session.serverTrustPolicyManager?.serverTrustPolicy(forHost: host),
let serverTrust = challenge.protectionSpace.serverTrust
{
if serverTrustPolicy.evaluate(serverTrust, forHost: host) {
disposition = .useCredential
credential = URLCredential(trust: serverTrust)
} else {
disposition = .cancelAuthenticationChallenge
}
}
} else {
if challenge.previousFailureCount > 0 {
disposition = .rejectProtectionSpace
} else {
credential = self.credential ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
completionHandler(disposition, credential)
}
@objc(URLSession:task:needNewBodyStream:)
func urlSession(
_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Void)
{
var bodyStream: InputStream?
if let taskNeedNewBodyStream = taskNeedNewBodyStream {
bodyStream = taskNeedNewBodyStream(session, task)
}
completionHandler(bodyStream)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: NSError?) {
if let taskDidCompleteWithError = taskDidCompleteWithError {
taskDidCompleteWithError(session, task, error)
} else {
if let error = error {
self.error = error
if
let downloadDelegate = self as? DownloadTaskDelegate,
let resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData] as? Data
{
downloadDelegate.resumeData = resumeData
}
}
queue.isSuspended = false
}
}
}
// MARK: -
class DataTaskDelegate: TaskDelegate, URLSessionDataDelegate {
// MARK: Properties
var dataTask: URLSessionDataTask? { return task as? URLSessionDataTask }
override var data: Data? {
if dataStream != nil {
return nil
} else {
return mutableData as Data
}
}
var dataProgress: ((_ bytesReceived: Int64, _ totalBytesReceived: Int64, _ totalBytesExpectedToReceive: Int64) -> Void)?
var dataStream: ((_ data: Data) -> Void)?
private var totalBytesReceived: Int64 = 0
private var mutableData: Data
private var expectedContentLength: Int64?
// MARK: Lifecycle
override init(task: URLSessionTask) {
mutableData = Data()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
var dataTaskDidReceiveResponse: ((URLSession, URLSessionDataTask, URLResponse) -> URLSession.ResponseDisposition)?
var dataTaskDidBecomeDownloadTask: ((URLSession, URLSessionDataTask, URLSessionDownloadTask) -> Void)?
var dataTaskDidReceiveData: ((URLSession, URLSessionDataTask, Data) -> Void)?
var dataTaskWillCacheResponse: ((URLSession, URLSessionDataTask, CachedURLResponse) -> CachedURLResponse?)?
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: ((URLSession.ResponseDisposition) -> Void))
{
var disposition: URLSession.ResponseDisposition = .allow
expectedContentLength = response.expectedContentLength
if let dataTaskDidReceiveResponse = dataTaskDidReceiveResponse {
disposition = dataTaskDidReceiveResponse(session, dataTask, response)
}
completionHandler(disposition)
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
{
dataTaskDidBecomeDownloadTask?(session, dataTask, downloadTask)
}
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let dataTaskDidReceiveData = dataTaskDidReceiveData {
dataTaskDidReceiveData(session, dataTask, data)
} else {
if let dataStream = dataStream {
dataStream(data)
} else {
mutableData.append(data)
}
let bytesReceived = Int64(data.count)
totalBytesReceived += bytesReceived
let totalBytesExpected = dataTask.response?.expectedContentLength ?? NSURLSessionTransferSizeUnknown
progress.totalUnitCount = totalBytesExpected
progress.completedUnitCount = totalBytesReceived
dataProgress?(
bytesReceived,
totalBytesReceived,
totalBytesExpected
)
}
}
func urlSession(
_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: ((CachedURLResponse?) -> Void))
{
var cachedResponse: CachedURLResponse? = proposedResponse
if let dataTaskWillCacheResponse = dataTaskWillCacheResponse {
cachedResponse = dataTaskWillCacheResponse(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
// MARK: -
class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate {
// MARK: Properties
var downloadTask: URLSessionDownloadTask? { return task as? URLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: Data?
override var data: Data? { return resumeData }
// MARK: NSURLSessionDownloadDelegate
var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)?
var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((URLSession, URLSessionDownloadTask, Int64, Int64) -> Void)?
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
{
if let downloadTaskDidFinishDownloadingToURL = downloadTaskDidFinishDownloadingToURL {
do {
let destination = downloadTaskDidFinishDownloadingToURL(session, downloadTask, location)
try FileManager.default.moveItem(at: location, to: destination)
} catch {
self.error = error as NSError
}
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64,
totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let downloadTaskDidWriteData = downloadTaskDidWriteData {
downloadTaskDidWriteData(
session,
downloadTask,
bytesWritten,
totalBytesWritten,
totalBytesExpectedToWrite
)
} else {
progress.totalUnitCount = totalBytesExpectedToWrite
progress.completedUnitCount = totalBytesWritten
downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
}
func urlSession(
_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
{
if let downloadTaskDidResumeAtOffset = downloadTaskDidResumeAtOffset {
downloadTaskDidResumeAtOffset(session, downloadTask, fileOffset, expectedTotalBytes)
} else {
progress.totalUnitCount = expectedTotalBytes
progress.completedUnitCount = fileOffset
}
}
}
// MARK: -
class UploadTaskDelegate: DataTaskDelegate {
// MARK: Properties
var uploadTask: URLSessionUploadTask? { return task as? URLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
var taskDidSendBodyData: ((URLSession, URLSessionTask, Int64, Int64, Int64) -> Void)?
func URLSession(
_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
{
if initialResponseTime == nil { initialResponseTime = CFAbsoluteTimeGetCurrent() }
if let taskDidSendBodyData = taskDidSendBodyData {
taskDidSendBodyData(session, task, bytesSent, totalBytesSent, totalBytesExpectedToSend)
} else {
progress.totalUnitCount = totalBytesExpectedToSend
progress.completedUnitCount = totalBytesSent
uploadProgress?(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
}
}
| 886b784bd8a980decf5f42d9a56725f7 | 34.92973 | 149 | 0.670679 | false | false | false | false |
wikimedia/apps-ios-wikipedia | refs/heads/twn | Wikipedia/Code/ReadingListsCollectionViewCell.swift | mit | 1 | class ReadingListsCollectionViewCell: ArticleCollectionViewCell {
private var bottomSeparator = UIView()
private var topSeparator = UIView()
private var articleCountLabel = UILabel()
var articleCount: Int64 = 0
private let imageGrid = UIView()
private var gridImageViews: [UIImageView] = []
private var isDefault: Bool = false
private let defaultListTag = UILabel() // explains that the default list cannot be deleted
private var singlePixelDimension: CGFloat = 0.5
private var displayType: ReadingListsDisplayType = .readingListsTab
override var alertType: ReadingListAlertType? {
didSet {
guard let alertType = alertType else {
return
}
var alertLabelText: String? = nil
switch alertType {
case .listLimitExceeded:
alertLabelText = WMFLocalizedString("reading-lists-list-not-synced-limit-exceeded", value: "List not synced, limit exceeded", comment: "Text of the alert label informing the user that list couldn't be synced.")
case .entryLimitExceeded:
alertLabelText = WMFLocalizedString("reading-lists-articles-not-synced-limit-exceeded", value: "Some articles not synced, limit exceeded", comment: "Text of the alert label informing the user that some articles couldn't be synced.")
default:
break
}
alertLabel.text = alertLabelText
if !isAlertIconHidden {
alertIcon.image = UIImage(named: "error-icon")
}
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
singlePixelDimension = traitCollection.displayScale > 0 ? 1.0 / traitCollection.displayScale : 0.5
}
override func setup() {
imageView.layer.cornerRadius = 3
bottomSeparator.isOpaque = true
contentView.addSubview(bottomSeparator)
topSeparator.isOpaque = true
contentView.addSubview(topSeparator)
contentView.addSubview(articleCountLabel)
contentView.addSubview(defaultListTag)
let topRow = UIStackView(arrangedSubviews: [UIImageView(), UIImageView()])
topRow.axis = NSLayoutConstraint.Axis.horizontal
topRow.distribution = UIStackView.Distribution.fillEqually
let bottomRow = UIStackView(arrangedSubviews: [UIImageView(), UIImageView()])
bottomRow.axis = NSLayoutConstraint.Axis.horizontal
bottomRow.distribution = UIStackView.Distribution.fillEqually
gridImageViews = (topRow.arrangedSubviews + bottomRow.arrangedSubviews).compactMap { $0 as? UIImageView }
gridImageViews.forEach {
$0.accessibilityIgnoresInvertColors = true
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
let outermostStackView = UIStackView(arrangedSubviews: [topRow, bottomRow])
outermostStackView.axis = NSLayoutConstraint.Axis.vertical
outermostStackView.distribution = UIStackView.Distribution.fillEqually
imageGrid.addSubview(outermostStackView)
outermostStackView.frame = imageGrid.frame
outermostStackView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageGrid.layer.cornerRadius = 3
imageGrid.masksToBounds = true
contentView.addSubview(imageGrid)
super.setup()
}
open override func reset() {
super.reset()
bottomSeparator.isHidden = true
topSeparator.isHidden = true
titleTextStyle = .semiboldBody
updateFonts(with: traitCollection)
}
override func updateFonts(with traitCollection: UITraitCollection) {
super.updateFonts(with: traitCollection)
articleCountLabel.font = UIFont.wmf_font(.caption2, compatibleWithTraitCollection: traitCollection)
defaultListTag.font = UIFont.wmf_font(.italicCaption2, compatibleWithTraitCollection: traitCollection)
}
override func updateBackgroundColorOfLabels() {
super.updateBackgroundColorOfLabels()
articleCountLabel.backgroundColor = labelBackgroundColor
defaultListTag.backgroundColor = labelBackgroundColor
}
override open func sizeThatFits(_ size: CGSize, apply: Bool) -> CGSize {
let size = super.sizeThatFits(size, apply: apply)
let layoutMargins = calculatedLayoutMargins
var widthMinusMargins = size.width - layoutMargins.left - layoutMargins.right
let minHeight = imageViewDimension + layoutMargins.top + layoutMargins.bottom
let minHeightMinusMargins = minHeight - layoutMargins.top - layoutMargins.bottom
let labelsAdditionalSpacing: CGFloat = 20
if !isImageGridHidden || !isImageViewHidden {
widthMinusMargins = widthMinusMargins - spacing - imageViewDimension - labelsAdditionalSpacing
}
var x = layoutMargins.left
if isDeviceRTL {
x = size.width - x - widthMinusMargins
}
var origin = CGPoint(x: x, y: layoutMargins.top)
if displayType == .readingListsTab {
let articleCountLabelSize = articleCountLabel.intrinsicContentSize
var x = origin.x
if isDeviceRTL {
x = size.width - articleCountLabelSize.width - layoutMargins.left
}
let articleCountLabelFrame = articleCountLabel.wmf_preferredFrame(at: CGPoint(x: x, y: origin.y), maximumSize: articleCountLabelSize, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += articleCountLabelFrame.layoutHeight(with: spacing)
articleCountLabel.isHidden = false
} else {
articleCountLabel.isHidden = true
}
let labelHorizontalAlignment: HorizontalAlignment = isDeviceRTL ? .right : .left
if displayType == .addArticlesToReadingList {
if isDefault {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: 0)
let descriptionLabelFrame = descriptionLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += descriptionLabelFrame.layoutHeight(with: 0)
} else {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: CGPoint(x: origin.x, y: layoutMargins.top), maximumSize: CGSize(width: widthMinusMargins, height: UIView.noIntrinsicMetric), minimumSize: CGSize(width: UIView.noIntrinsicMetric, height: minHeightMinusMargins), horizontalAlignment: labelHorizontalAlignment, verticalAlignment: .center, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: 0)
}
} else if (descriptionLabel.wmf_hasText || !isImageGridHidden || !isImageViewHidden) {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: spacing)
let descriptionLabelFrame = descriptionLabel.wmf_preferredFrame(at: origin, maximumWidth: widthMinusMargins, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += descriptionLabelFrame.layoutHeight(with: 0)
} else {
let titleLabelFrame = titleLabel.wmf_preferredFrame(at: origin, maximumSize: CGSize(width: widthMinusMargins, height: UIView.noIntrinsicMetric), minimumSize: CGSize(width: UIView.noIntrinsicMetric, height: minHeightMinusMargins), horizontalAlignment: labelHorizontalAlignment, verticalAlignment: .center, apply: apply)
origin.y += titleLabelFrame.layoutHeight(with: 0)
if !isAlertIconHidden || !isAlertLabelHidden {
origin.y += titleLabelFrame.layoutHeight(with: spacing) + spacing * 2
}
}
descriptionLabel.isHidden = !descriptionLabel.wmf_hasText
origin.y += layoutMargins.bottom
let height = max(origin.y, minHeight)
let separatorXPositon: CGFloat = 0
let separatorWidth = size.width
if (apply) {
if (!bottomSeparator.isHidden) {
bottomSeparator.frame = CGRect(x: separatorXPositon, y: height - singlePixelDimension, width: separatorWidth, height: singlePixelDimension)
}
if (!topSeparator.isHidden) {
topSeparator.frame = CGRect(x: separatorXPositon, y: 0, width: separatorWidth, height: singlePixelDimension)
}
}
if (apply) {
let imageViewY = floor(0.5*height - 0.5*imageViewDimension)
var x = layoutMargins.right
if !isDeviceRTL {
x = size.width - x - imageViewDimension
}
imageGrid.frame = CGRect(x: x, y: imageViewY, width: imageViewDimension, height: imageViewDimension)
imageGrid.isHidden = isImageGridHidden
}
if (apply && !isImageViewHidden) {
let imageViewY = floor(0.5*height - 0.5*imageViewDimension)
var x = layoutMargins.right
if !isDeviceRTL {
x = size.width - x - imageViewDimension
}
imageView.frame = CGRect(x: x, y: imageViewY, width: imageViewDimension, height: imageViewDimension)
}
let yAlignedWithImageBottom = imageGrid.frame.maxY - layoutMargins.bottom - (0.5 * spacing)
if !isAlertIconHidden {
var x = origin.x
if isDeviceRTL {
x = size.width - alertIconDimension - layoutMargins.right
}
alertIcon.frame = CGRect(x: x, y: yAlignedWithImageBottom, width: alertIconDimension, height: alertIconDimension)
origin.y += alertIcon.frame.layoutHeight(with: 0)
}
if !isAlertLabelHidden {
var xPosition = alertIcon.frame.maxX + spacing
var yPosition = alertIcon.frame.midY - 0.5 * alertIconDimension
var availableWidth = widthMinusMargins - alertIconDimension - spacing
if isDeviceRTL {
xPosition = alertIcon.frame.minX - availableWidth - spacing
}
if isAlertIconHidden {
xPosition = origin.x
yPosition = yAlignedWithImageBottom
availableWidth = widthMinusMargins
}
let alertLabelFrame = alertLabel.wmf_preferredFrame(at: CGPoint(x: xPosition, y: yPosition), maximumWidth: availableWidth, alignedBy: articleSemanticContentAttribute, apply: apply)
origin.y += alertLabelFrame.layoutHeight(with: 0)
}
if displayType == .readingListsTab && isDefault {
let defaultListTagSize = defaultListTag.intrinsicContentSize
var x = origin.x
if isDeviceRTL {
x = size.width - defaultListTagSize.width - layoutMargins.right
}
var y = yAlignedWithImageBottom
if !isAlertIconHidden || !isAlertLabelHidden {
let alertMinY = isAlertIconHidden ? alertLabel.frame.minY : alertIcon.frame.minY
y = descriptionLabel.frame.maxY + ((alertMinY - descriptionLabel.frame.maxY) * 0.25)
}
_ = defaultListTag.wmf_preferredFrame(at: CGPoint(x: x, y: y), maximumSize: defaultListTagSize, alignedBy: articleSemanticContentAttribute, apply: apply)
defaultListTag.isHidden = false
} else {
defaultListTag.isHidden = true
}
return CGSize(width: size.width, height: height)
}
override func configureForCompactList(at index: Int) {
layoutMarginsAdditions.top = 5
layoutMarginsAdditions.bottom = 5
titleTextStyle = .subheadline
descriptionTextStyle = .footnote
updateFonts(with: traitCollection)
imageViewDimension = 40
}
private var isImageGridHidden: Bool = false {
didSet {
imageGrid.isHidden = isImageGridHidden
setNeedsLayout()
}
}
func configureAlert(for readingList: ReadingList, listLimit: Int, entryLimit: Int) {
guard let error = readingList.APIError else {
return
}
switch error {
case .listLimit:
isAlertLabelHidden = false
isAlertIconHidden = false
alertType = .listLimitExceeded(limit: listLimit)
case .entryLimit:
isAlertLabelHidden = false
isAlertIconHidden = false
alertType = .entryLimitExceeded(limit: entryLimit)
default:
isAlertLabelHidden = true
isAlertIconHidden = true
}
let isAddArticlesToReadingListDisplayType = displayType == .addArticlesToReadingList
isAlertIconHidden = isAddArticlesToReadingListDisplayType
isAlertLabelHidden = isAddArticlesToReadingListDisplayType
}
func configure(readingList: ReadingList, isDefault: Bool = false, index: Int, shouldShowSeparators: Bool = false, theme: Theme, for displayType: ReadingListsDisplayType, articleCount: Int64, lastFourArticlesWithLeadImages: [WMFArticle], layoutOnly: Bool) {
configure(with: readingList.name, description: readingList.readingListDescription, isDefault: isDefault, index: index, shouldShowSeparators: shouldShowSeparators, theme: theme, for: displayType, articleCount: articleCount, lastFourArticlesWithLeadImages: lastFourArticlesWithLeadImages, layoutOnly: layoutOnly)
}
func configure(with name: String?, description: String?, isDefault: Bool = false, index: Int, shouldShowSeparators: Bool = false, theme: Theme, for displayType: ReadingListsDisplayType, articleCount: Int64, lastFourArticlesWithLeadImages: [WMFArticle], layoutOnly: Bool) {
articleSemanticContentAttribute = .unspecified
imageViewDimension = 100
self.displayType = displayType
self.isDefault = isDefault
self.articleCount = articleCount
articleCountLabel.text = String.localizedStringWithFormat(CommonStrings.articleCountFormat, articleCount).uppercased()
defaultListTag.text = WMFLocalizedString("saved-default-reading-list-tag", value: "This list cannot be deleted", comment: "Tag on the default reading list cell explaining that the list cannot be deleted")
titleLabel.text = name
descriptionLabel.text = description
let imageWidthToRequest = imageView.frame.size.width < 300 ? traitCollection.wmf_nearbyThumbnailWidth : traitCollection.wmf_leadImageWidth
let imageURLs = lastFourArticlesWithLeadImages.compactMap { $0.imageURL(forWidth: imageWidthToRequest) }
isImageGridHidden = imageURLs.count != 4 // we need 4 images for the grid
isImageViewHidden = !(isImageGridHidden && imageURLs.count >= 1) // we need at least one image to display
if !layoutOnly && !isImageGridHidden {
let _ = zip(gridImageViews, imageURLs).compactMap { $0.wmf_setImage(with: $1, detectFaces: true, onGPU: true, failure: { (error) in }, success: { })}
}
if isImageGridHidden, let imageURL = imageURLs.first {
if !layoutOnly {
imageView.wmf_setImage(with: imageURL, detectFaces: true, onGPU: true, failure: { (error) in }, success: { })
}
} else {
isImageViewHidden = true
}
if displayType == .addArticlesToReadingList {
configureForCompactList(at: index)
}
if shouldShowSeparators {
topSeparator.isHidden = index > 0
bottomSeparator.isHidden = false
} else {
bottomSeparator.isHidden = true
}
apply(theme: theme)
extractLabel?.text = nil
setNeedsLayout()
}
public override func apply(theme: Theme) {
super.apply(theme: theme)
bottomSeparator.backgroundColor = theme.colors.border
topSeparator.backgroundColor = theme.colors.border
articleCountLabel.textColor = theme.colors.secondaryText
defaultListTag.textColor = theme.colors.secondaryText
}
}
| 032e7fb368179d7a92b9b17c21b6261d | 46.902579 | 370 | 0.656478 | false | false | false | false |
ResearchSuite/ResearchSuiteExtensions-iOS | refs/heads/master | Example/Pods/ResearchSuiteTaskBuilder/ResearchSuiteTaskBuilder/Classes/Step Providers/Generators/RSTBChoiceStepGenerator.swift | apache-2.0 | 1 | //
// RSTBChoiceStepGenerator.swift
// Pods
//
// Created by James Kizer on 1/9/17.
//
//
import ResearchKit
import Gloss
open class RSTBChoiceStepGenerator: RSTBQuestionStepGenerator {
open var allowsMultiple: Bool {
fatalError("abstract class not implemented")
}
public typealias ChoiceItemFilter = ( (RSTBChoiceItemDescriptor) -> (Bool))
open func generateFilter(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ChoiceItemFilter? {
return { choiceItem in
return true
}
}
open func generateChoices(items: [RSTBChoiceItemDescriptor], valueSuffix: String?, shouldShuffle: Bool?) -> [ORKTextChoice] {
let shuffledItems = items.shuffled(shouldShuffle: shouldShuffle ?? false)
return shuffledItems.map { item in
let value: NSCoding & NSCopying & NSObjectProtocol = ({
if let suffix = valueSuffix,
let stringValue = item.value as? String {
return (stringValue + suffix) as NSCoding & NSCopying & NSObjectProtocol
}
else {
return item.value
}
}) ()
return ORKTextChoice(
text: item.text,
detailText: item.detailText,
value: value,
exclusive: item.exclusive)
}
}
override open func generateAnswerFormat(type: String, jsonObject: JSON, helper: RSTBTaskBuilderHelper) -> ORKAnswerFormat? {
guard let choiceStepDescriptor = RSTBChoiceStepDescriptor(json: jsonObject) else {
return nil
}
let filteredItems: [RSTBChoiceItemDescriptor] = {
if let itemFilter = self.generateFilter(type: type, jsonObject: jsonObject, helper: helper) {
return choiceStepDescriptor.items.filter(itemFilter)
}
else {
return choiceStepDescriptor.items
}
}()
let choices = self.generateChoices(items: filteredItems, valueSuffix: choiceStepDescriptor.valueSuffix, shouldShuffle: choiceStepDescriptor.shuffleItems)
guard choices.count > 0 else {
return nil
}
let answerFormat = ORKAnswerFormat.choiceAnswerFormat(
with: self.allowsMultiple ? ORKChoiceAnswerStyle.multipleChoice : ORKChoiceAnswerStyle.singleChoice,
textChoices: choices
)
return answerFormat
}
open override func processQuestionResult(type: String, result: ORKQuestionResult, helper: RSTBTaskBuilderHelper) -> JSON? {
if let result = result as? ORKChoiceQuestionResult,
let choices = result.choiceAnswers as? [NSCoding & NSCopying & NSObjectProtocol] {
return [
"identifier": result.identifier,
"type": type,
"answer": choices
]
}
return nil
}
}
open class RSTBSingleChoiceStepGenerator: RSTBChoiceStepGenerator {
public override init(){}
override open var supportedTypes: [String]! {
return ["singleChoiceText"]
}
override open var allowsMultiple: Bool {
return false
}
}
open class RSTBMultipleChoiceStepGenerator: RSTBChoiceStepGenerator {
public override init(){}
override open var supportedTypes: [String]! {
return ["multipleChoiceText"]
}
override open var allowsMultiple: Bool {
return true
}
}
| adfa15082767e4eee601eb50f5bbfb22 | 29.347107 | 161 | 0.590959 | false | false | false | false |
tectijuana/iOS | refs/heads/master | MaldonadoAntonio/Calculadora/Calculadora/ViewController.swift | mit | 2 | //
// ViewController.swift
// Calculadora
//
// Created by user on 11/11/16.
// Copyright (c) 2016 cris. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
var userIsInTheMiddleOfTypingANumber: Bool = false
@IBAction func appenDigit(_ sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber{
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}
}
@IBAction func operate(_ sender: UIButton) {
let operacion = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operacion {
case "X": performOperacion { $0 * $1 }
case "÷": performOperacion { $1 / $0 }
case "✚": performOperacion { $0 + $1 }
case "−": performOperacion { $1 - $0 }
case "💩": performOperacion2 { sqrt($0) }
default: break
}
}
func performOperacion(_ operacion: (Double, Double) -> Double) {
if operacionStack.count >= 2 {
displayValue = operacion(operacionStack.removeLast(), operacionStack.removeLast())
enter()
}
}
func performOperacion2(_ operacion: (Double) -> Double) {
if operacionStack.count >= 1 {
displayValue = operacion(operacionStack.removeLast())
enter()
}
}
var operacionStack = Array<Double>()
@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operacionStack.append(displayValue)
print("operacionStack", operacionStack)
}
var displayValue: Double {
get {
return NumberFormatter().number(from: display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}
| c5cc3957c9df0fbc8550b595054249d9 | 26.026316 | 94 | 0.568647 | false | false | false | false |
robbdimitrov/pixelgram-ios | refs/heads/master | PixelGram/Classes/Screens/Feed/FeedViewController.swift | mit | 1 | //
// FeedViewController.swift
// PixelGram
//
// Created by Robert Dimitrov on 10/27/17.
// Copyright © 2017 Robert Dimitrov. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class FeedViewController: CollectionViewController {
var viewModel = FeedViewModel()
private var dataSource: CollectionViewDataSource?
private var selectedIndex: Int?
// MARK: - View lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setupRefreshControl()
setupViewModel()
setupUserLoadedNotification()
setupLogoutNotification()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if viewModel.numberOfItems <= 0 {
viewModel.loadData()
}
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
if let collectionView = collectionView, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: collectionView.frame.width, height: collectionView.frame.width)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
displayLoginScreen()
}
// MARK: - Notifications
private func setupLogoutNotification() {
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: APIClient.UserLoggedInNotification),
object: APIClient.shared, queue: nil, using: { [weak self] notification in
self?.viewModel.page = 0
self?.viewModel.images.value.removeAll()
self?.displayLoginScreen()
})
}
private func setupUserLoadedNotification() {
NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: UserLoader.UserLoadedNotification),
object: UserLoader.shared, queue: nil, using: { [weak self] notification in
guard let user = notification.userInfo?["user"] as? User else {
return
}
self?.reloadVisibleCells(user.id)
})
}
// MARK: - Data
override func handleRefresh(_ sender: UIRefreshControl) {
viewModel.page = 0
if viewModel.type != .single {
viewModel.images.value.removeAll()
}
viewModel.loadData()
}
private func reloadVisibleCells(_ userId: String) {
guard let collectionView = collectionView else {
return
}
let visibleCells = collectionView.visibleCells
for cell in visibleCells {
if let cell = cell as? ImageViewCell, cell.viewModel?.image.owner == userId, let indexPath = collectionView.indexPath(for: cell) {
setupCell(cell, forIndexPath: indexPath)
}
}
}
private func createDataSource() -> CollectionViewDataSource {
let dataSource = CollectionViewDataSource(configureCell: { [weak self] (collectionView, indexPath) -> UICollectionViewCell in
if indexPath.row == (self?.viewModel.images.value.count ?? 0) - 1 {
self?.viewModel.loadData()
}
return (self?.configureCell(collectionView: collectionView, indexPath: indexPath))!
}, numberOfItems: { [weak self] (collectionView, section) -> Int in
return self?.viewModel.numberOfItems ?? 0
})
return dataSource
}
// MARK: - Cells
private func configureCell(collectionView: UICollectionView, indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ImageViewCell.reuseIdentifier, for: indexPath)
setupCell(cell, forIndexPath: indexPath)
return cell
}
private func setupCell(_ cell: UICollectionViewCell, forIndexPath indexPath: IndexPath) {
guard let cell = cell as? ImageViewCell else {
return
}
let imageViewModel = viewModel.imageViewModel(forIndex: indexPath.row)
cell.configure(with: imageViewModel)
cell.userButton?.rx.tap.subscribe(onNext: { [weak self] in
self?.openUserProfile(atIndex: indexPath.row)
}).disposed(by: cell.disposeBag)
cell.likesButton?.rx.tap.subscribe(onNext: { [weak self] in
self?.openLikedUsers(selectedIndex: indexPath.row)
}).disposed(by: cell.disposeBag)
cell.optionsButton?.rx.tap.subscribe(onNext: { [weak self] in
self?.selectedIndex = indexPath.row
self?.openOptions()
}).disposed(by: cell.disposeBag)
}
private func updateCells(oldCount: Int, count: Int) {
guard let collectionView = collectionView else {
return
}
if oldCount == count {
refreshCells(collectionView: collectionView)
} else if oldCount < count {
insertCells(collectionView: collectionView, oldCount: oldCount, count: count)
} else if oldCount > count {
collectionView.reloadData()
}
}
private func insertCells(collectionView: UICollectionView, oldCount: Int, count: Int) {
var indexPaths = [IndexPath]()
for index in oldCount...(count - 1) {
let indexPath = IndexPath(row: index, section: 0)
indexPaths.append(indexPath)
}
if oldCount == 0 {
collectionView.reloadData()
} else {
collectionView.insertItems(at: indexPaths)
}
}
private func refreshCells(collectionView: UICollectionView) {
for cell in collectionView.visibleCells {
if let indexPath = collectionView.indexPath(for: cell) {
setupCell(cell, forIndexPath: indexPath)
}
}
}
// MARK: - Config
private func setupViewModel() {
viewModel.loadingFinished = { [weak self] (oldCount, count) in
if self?.collectionView?.refreshControl?.isRefreshing ?? false {
self?.collectionView?.refreshControl?.endRefreshing()
}
self?.updateCells(oldCount: oldCount, count: count)
}
viewModel.loadingFailed = { [weak self] error in
self?.showError(error: error)
}
}
private func setupRefreshControl() {
collectionView?.alwaysBounceVertical = true
collectionView?.refreshControl = refreshControl
}
override func setupNavigationItem() {
super.setupNavigationItem()
title = viewModel.title
if viewModel.type == .feed, let image = UIImage(named: "logo") {
setupTitleView(with: image)
}
}
override func configureCollectionView() {
guard let collectionView = collectionView else {
print("Error: collection view is nil")
return
}
let dataSource = createDataSource()
self.dataSource = dataSource
collectionView.dataSource = dataSource
}
// MARK: - Actions
private func displayLoginScreen() {
if Session.shared.currentUser == nil {
let viewController = instantiateViewController(withIdentifier: LoginViewController.storyboardIdentifier)
present(NavigationController(rootViewController: viewController), animated: true, completion: nil)
}
}
private func openOptions() {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
// Cancel action
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
// Delete action
alertController.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] action in
self?.deleteAction()
})
present(alertController, animated: true, completion: nil)
}
private func deleteAction() {
let alertController = UIAlertController(title: "Delete Post?", message: "Do you want to delete the post permanently?",
preferredStyle: .alert)
// Cancel action
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
// Delete action
alertController.addAction(UIAlertAction(title: "Delete", style: .destructive) { [weak self] action in
if let selectedIndex = self?.selectedIndex {
self?.deleteImage(atIndex: selectedIndex)
self?.selectedIndex = nil
}
})
present(alertController, animated: true, completion: nil)
}
private func deleteImage(atIndex index: Int) {
let imageId = viewModel.images.value[index].id
let indexPath = IndexPath(row: index, section: 0)
view.window?.showLoadingHUD()
APIClient.shared.deleteImage(withId: imageId, completion: { [weak self] in
self?.view.window?.hideLoadingHUD()
self?.viewModel.images.value.remove(at: index)
self?.collectionView?.deleteItems(at: [indexPath])
if self?.viewModel.type == .single, self?.viewModel.numberOfItems == 0 {
self?.navigationController?.popViewController(animated: true)
}
}) { [weak self] error in
self?.view.window?.hideLoadingHUD()
self?.showError(error: error)
}
}
// MARK: - Navigation
private func openUserProfile(atIndex index: Int) {
let imageOwner = viewModel.images.value[index].owner
openUserProfile(withUserId: imageOwner)
}
private func openUserProfile(withUserId userId: String) {
let viewController = instantiateViewController(withIdentifier:
ProfileViewController.storyboardIdentifier)
(viewController as? ProfileViewController)?.userId = userId
navigationController?.pushViewController(viewController, animated: true)
}
private func openLikedUsers(selectedIndex: Int) {
let image = viewModel.images.value[selectedIndex]
if image.likes < 1 {
return
}
let viewController = instantiateViewController(withIdentifier:
UsersViewController.storyboardIdentifier)
(viewController as? UsersViewController)?.viewModel = UsersViewModel(with: image.id)
navigationController?.pushViewController(viewController, animated: true)
}
// MARK: - Object lifecycle
deinit {
NotificationCenter.default.removeObserver(self)
}
}
| 3bee4b0ef7ae03fa157836a0a8853d63 | 34.163462 | 142 | 0.611977 | false | false | false | false |
hnney/SwiftReeder | refs/heads/master | SwiftReeder/Core/FeedManager.swift | apache-2.0 | 2 | //
// FeedManager.swift
// SwiftReeder
//
// Created by Thilong on 14/6/5.
// Copyright (c) 2014年 thilong. All rights reserved.
//
import Foundation
var global_FeedManager : FeedManager!
class FeedManager{
var _data : NSMutableArray = NSMutableArray()
class func sharedManager()->FeedManager!{
if !global_FeedManager{
global_FeedManager = FeedManager()
}
return global_FeedManager;
}
init(){
}
func addFeed(feed : Feed){
for fe : AnyObject in self._data
{
if fe.name == feed.name{
return;
}
}
self._data.addObject(feed);
self.saveAllFeeds();
}
func removeFeedAtIndex(index : Int){
self._data.removeObjectAtIndex(index);
self.saveAllFeeds();
}
func feedsCount()->Int{
return self._data.count;
}
func feedAtIndex(index : Int)->Feed!{
return self._data.objectAtIndex(index) as Feed;
}
func saveAllFeeds(){
var path : String! = OCBridge.feedCachePath(false);
if path{
NSFileManager.defaultManager().removeItemAtPath(path,error:nil);
}
NSKeyedArchiver.archiveRootObject(_data,toFile: path);
}
func loadAllFeeds(){
var path : String! = OCBridge.feedCachePath(true);
if path{
var arrays = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as NSArray;
_data.addObjectsFromArray(arrays);
}
}
} | 4567755e4429175870917f4d31d08a8a | 21.652174 | 84 | 0.567222 | false | false | false | false |
Hout/DateInRegion | refs/heads/master | Pod/Classes/DateInRegionDescription.swift | mit | 1 | //
// DateInRegionDescription.swift
// Pods
//
// Created by Jeroen Houtzager on 26/10/15.
//
//
import Foundation
// MARK: - CustomStringConvertable delegate
extension DateInRegion : CustomDebugStringConvertible {
/// Returns a full description of the class
///
public var description: String {
return "\(self.toString()!); region: \(region)"
}
/// Returns a full debug description of the class
///
public var debugDescription: String {
var descriptor: [String] = []
let formatter = NSDateFormatter()
formatter.dateStyle = .LongStyle
formatter.timeStyle = .LongStyle
formatter.locale = self.locale
formatter.calendar = self.calendar
formatter.timeZone = NSTimeZone(abbreviation: "UTC")
descriptor.append("UTC\t\(formatter.stringFromDate(self.date))")
formatter.timeZone = self.timeZone
descriptor.append("Local\t\(formatter.stringFromDate(self.date))")
descriptor.append("Calendar: \(calendar.calendarIdentifier)")
descriptor.append("Time zone: \(timeZone.name)")
descriptor.append("Locale: \(locale.localeIdentifier)")
return descriptor.joinWithSeparator("\n")
}
}
| ee9dc43a5d68a5a398ec22214f0cc6d3 | 26.488889 | 74 | 0.658852 | false | false | false | false |
tasanobu/PullToRefreshSwift | refs/heads/master | Example/PullToRefreshSwift/ViewController.swift | mit | 1 | //
// PullToRefreshConst.swift
// PullToRefreshSwift
//
// Created by Yuji Hato on 12/11/14.
//
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate {
@IBOutlet weak var tableView: UITableView!
var texts = ["Swift", "Java", "Objective-C", "Perl", "C", "C++", "Ruby", "Javascript", "Go", "PHP", "Python", "Scala"]
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Sample"
self.tableView.separatorColor = UIColor(red: 224/255, green: 224/255, blue: 224/255, alpha: 1.0)
self.tableView.addPullToRefresh({ [weak self] in
// some code
sleep(1)
self?.texts.shuffle()
self?.tableView.reloadData()
//self?.tableView.stopPullToRefresh()
})
}
override func viewDidAppear(animated: Bool) {
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return texts.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel?.font = UIFont.italicSystemFontOfSize(18)
cell.textLabel?.textColor = UIColor(red: 44/255, green: 62/255, blue: 88/255, alpha: 1.0)
cell.textLabel?.text = texts[indexPath.row]
return cell
}
func scrollViewDidScroll(scrollView: UIScrollView) {
self.tableView.fixedPullToRefreshViewForDidScroll()
}
}
| 8219cd8eb9e2c4c63ff4e796f3ef44fe | 31.849057 | 122 | 0.648478 | false | false | false | false |
TMTBO/TTARefresher | refs/heads/master | TTARefresher/Classes/Header/TTARefresherNormalHeader.swift | mit | 1 | //
// TTARefresherNormalHeader.swift
// Pods
//
// Created by TobyoTenma on 12/05/2017.
//
//
import UIKit
open class TTARefresherNormalHeader: TTARefresherStateHeader {
public var indicatotStyle = UIActivityIndicatorViewStyle.gray {
didSet {
loadingView = nil
setNeedsLayout()
}
}
public lazy var arrowImageView: UIImageView = {
let arrowImage = Bundle.TTARefresher.arrowImage()
let arrowImageView = UIImageView(image: arrowImage)
self.addSubview(arrowImageView)
return arrowImageView
}()
lazy var loadingView: UIActivityIndicatorView? = {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: self.indicatotStyle)
indicator.hidesWhenStopped = true
self.addSubview(indicator)
return indicator
}()
open override var state: TTARefresherState {
didSet {
if oldValue == state { return }
if state == .idle {
if oldValue == .refreshing {
arrowImageView.transform = .identity
UIView.animate(withDuration: TTARefresherAnimationDuration.slow, animations: { [weak self] in
guard let `self` = self else { return }
self.loadingView?.alpha = 0
}, completion: { [weak self] (isFinished) in
guard let `self` = self else { return }
if self.state != .idle { return }
self.loadingView?.alpha = 1
self.loadingView?.stopAnimating()
self.arrowImageView.isHidden = false
})
} else {
loadingView?.stopAnimating()
arrowImageView.isHidden = false
UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in
guard let `self` = self else { return }
self.arrowImageView.transform = .identity
})
}
} else if state == .pulling {
loadingView?.stopAnimating()
arrowImageView.isHidden = false
UIView.animate(withDuration: TTARefresherAnimationDuration.fast, animations: { [weak self] in
guard let `self` = self else { return }
self.arrowImageView.transform = CGAffineTransform(rotationAngle: 0.000001 - CGFloat.pi)
})
} else if state == .refreshing {
loadingView?.alpha = 1
loadingView?.startAnimating()
arrowImageView.isHidden = true
}
}
}
}
// MARK: - Override Methods
extension TTARefresherNormalHeader {
override open func placeSubviews() {
super.placeSubviews()
var arrowCenterX = bounds.width * 0.5
if !stateLabel.isHidden {
let stateWidth = stateLabel.ttaRefresher.textWidth()
var timeWidth: CGFloat = 0
if !lastUpdatedTimeLabel.isHidden {
timeWidth = lastUpdatedTimeLabel.ttaRefresher.textWidth()
}
let textWidth = max(stateWidth, timeWidth)
arrowCenterX -= textWidth / 2 + labelLeftInset
}
let arrowCenterY = bounds.height * 0.5
let arrowCenter = CGPoint(x: arrowCenterX, y: arrowCenterY)
if arrowImageView.constraints.count == 0, let image = arrowImageView.image {
arrowImageView.bounds.size = image.size
arrowImageView.center = arrowCenter
}
if loadingView?.constraints.count == 0 {
loadingView?.center = arrowCenter
}
arrowImageView.tintColor = stateLabel.textColor
}
}
| e222b7b77cde3495195dc4a2e05ed6a4 | 36.598039 | 113 | 0.56558 | false | false | false | false |
stomp1128/TIY-Assignments | refs/heads/master | TackyTacTac/TackyTacTac/ViewController.swift | cc0-1.0 | 1 | //
// ViewController.swift
// TackyTacTac
//
// Created by Chris Stomp on 10/26/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
//
//import UIKit
//
//class ViewController: UIViewController {
//
// var grid = [[0,0,0], [0,0,0], [0,0,0]] //2
//
// var isPlayer1Turn = true // step 2 set the rest of the properties
//
// var player1Score = 0 //2
// var player2Score = 0 //2
// var stalemateScore = 0 //2
//
// let gameStatusLabel = UILabel(frame: CGRect(x: 0, y: 80, width: 200, height: 50)) //step 1
//
// override func viewDidLoad()
// {
// super.viewDidLoad()
// view.backgroundColor = UIColor.whiteColor() //step 3 background color
//
// gameStatusLabel.text = "Player 1 Turn" //step 4
// gameStatusLabel.textAlignment = .Center
//
// gameStatusLabel.center.x = view.center.x
//
// view.addSubview(gameStatusLabel) //step 5 add it as subview to make it visible on screen
//
// let screenHeight = Int(UIScreen.mainScreen().bounds.height) //step 6
// let screenWidth = Int(UIScreen.mainScreen().bounds.width)
//
// let buttonHW = 100
// let buttonSpacing = 4
//
// let gridHW = (buttonHW * 3) + (buttonSpacing * 2)
//
// let leftSpacing = (screenWidth - gridHW) / 2
// let topSpacing = (screenHeight - gridHW) / 2
//
// for (r, row) in grid.enumerate() // step 7 set up grid
// {
// for (c, _) in row.enumerate()
// {
// let x = c * (buttonHW + buttonSpacing) + leftSpacing
// let y = r * (buttonHW + buttonSpacing) + topSpacing
// let button = TTTButton(frame: CGRect(x: x, y: y, width: buttonHW, height: buttonHW)) //step 9
// button.backgroundColor = UIColor.cyanColor()
//
// button.row = r
// button.col = c
//
// button.addTarget(self, action: "spacePressed:", forControlEvents: .TouchUpInside) // name of func in quotes, colon becuase it takes an argument
// view.addSubview(button)
// }
// }
// }
//
// override func didReceiveMemoryWarning()
// {
// super.didReceiveMemoryWarning()
//
// // MARK = Action Handlers
//
// func spacePressed(button: TTTButton) //step 10
// {
// if button.player == 0
// {
//// if isPlayer1Turn
//// {
//// button.player = 1
//// }
//// else
//// {
//// button.player = 2
//// }
// button.player = isPlayer1Turn ? 1 : 2
//
// grid[button.row] [button.col] = isPlayer1Turn ? 1 : 2 //record which button has been pressed by which player
//
// isPlayer1Turn = !isPlayer1Turn // decide whose turn it is
//
// checkForWinner() //func to decide if there is a winner
//
// }
// }
// }
//
// // MARK - Misc.
//
// func checkForWinner()
// {
// let possibilities = [
// ((0,0),(0,1),(0,2)),
// ((1,0),(1,1),(1,2)),
// ((2,0),(2,1),(2,2)),
// ((0,0),(1,0),(2,0)),
// ((0,1),(1,1),(2,1)),
// ((0,2),(1,2),(2,2)),
// ((0,0),(1,1),(2,2)),
// ((2,0),(1,1),(0,2))
// ]
//
// for possibility in possibilities
// {
// let (p1,p2,p3) = possibility
// let value1 = grid[p1.0][p1.1]
// let value2 = grid[p2.0][p2.1]
// let value3 = grid[p3.0][p3.1]
//
// if value1 == value2 && value2 == value3
// {
// if value1 != 0
// {
// print("Player \(value1) wins!")
// }
// else
// {
// print("No winner: all zeros")
// }
// }
// else
// {
// print("Does not match")
// }
// }
// }
//
//
//}
//
//class TTTButton: UIButton // step 8 set up new class and name it
//{
// var row = 0
// var col = 0
//
// var player = 0 {
// didSet {
// switch player {
// case 1: backgroundColor = UIColor.magentaColor()
// case 2: backgroundColor = UIColor.yellowColor()
// default: backgroundColor = UIColor.cyanColor()
// }
// }
// }
//
//}
import UIKit
class ViewController: UIViewController
{
var grid = [[0,0,0], [0,0,0], [0,0,0]]
var playButtons = [TTTButton]()
var isPlayer1Turn = true
var player1Score = 0
var player2Score = 0
var stalemateScore = 0
let gameStatusLabel = UILabel(frame: CGRect(x: 0, y: 80, width: 200, height: 50))
let player1ScoreLabel = UILabel(frame: CGRect(x: 0, y: 560, width: 200, height: 50))
let player2ScoreLabel = UILabel(frame: CGRect(x: 0, y: 580, width: 200, height: 50))
let stalemateScoreLabel = UILabel(frame: CGRect(x: 0, y: 620, width: 200, height: 50))
override func viewDidLoad()
{
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
gameStatusLabel.text = "Player 1 Turn"
gameStatusLabel.textAlignment = .Center
gameStatusLabel.center.x = view.center.x
player1ScoreLabel.text = "Player 1 Score = 0"
player1ScoreLabel.textAlignment = .Center
player1ScoreLabel.center.x = view.center.x
player2ScoreLabel.text = "Player 2 Score = 0"
player2ScoreLabel.textAlignment = .Center
player2ScoreLabel.center.x = view.center.x
stalemateScoreLabel.text = "Stalemate = 0"
stalemateScoreLabel.textAlignment = .Center
stalemateScoreLabel.center.x = view.center.x
let resetButton = UIButton(type: UIButtonType.System) as UIButton
resetButton.frame = CGRectMake(0, 660, 100, 50)
resetButton.backgroundColor = UIColor.cyanColor()
resetButton.setTitle("Reset", forState: UIControlState.Normal)
resetButton.addTarget(self, action: "resetButton:", forControlEvents: UIControlEvents.TouchUpInside)
resetButton.center.x = view.center.x
self.view.addSubview(resetButton)
view.addSubview(gameStatusLabel)
view.addSubview(player1ScoreLabel)
view.addSubview(player2ScoreLabel)
view.addSubview(stalemateScoreLabel)
let screenHeight = Int(UIScreen.mainScreen().bounds.height)
let screenWidth = Int(UIScreen.mainScreen().bounds.width)
let buttonHW = 100
let buttonSpacing = 4
let gridHW = (buttonHW * 3) + (buttonSpacing * 2)
let leftSpacing = (screenWidth - gridHW) / 2
let topSpacing = (screenHeight - gridHW) / 2
for (r, row) in grid.enumerate()
{
for (c, _) in row.enumerate()
{
let x = c * (buttonHW + buttonSpacing) + leftSpacing
let y = r * (buttonHW + buttonSpacing) + topSpacing
let button = TTTButton(frame: CGRect(x: x, y: y, width: buttonHW, height: buttonHW))
button.backgroundColor = UIColor.cyanColor()
button.row = r
button.col = c
button.addTarget(self, action: "spacePressed:", forControlEvents: .TouchUpInside)
view.addSubview(button)
playButtons.append(button)
}
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Action Handlers
func spacePressed(button: TTTButton)
{
if button.player == 0
{
// if isPlayer1Turn
// {
// button.player = 1
// }
// else
// {
// button.player = 2
// }
button.player = isPlayer1Turn ? 1 : 2
grid[button.row][button.col] = isPlayer1Turn ? 1 : 2
isPlayer1Turn = !isPlayer1Turn
if isPlayer1Turn == true
{
gameStatusLabel.text = "Player 1 Turn"
}
if isPlayer1Turn == false
{
gameStatusLabel.text = "Player 2 Turn"
}
checkForWinner()
}
}
func resetButton(sender:UIButton!)
{
for aButton in playButtons
{
grid = [[0,0,0], [0,0,0], [0,0,0]]
aButton.player = 0
}
}
// MARK: - Misc.
func checkForWinner()
{
var stalemateCount = 0
let possibilities = [
((0,0),(0,1),(0,2)),
((1,0),(1,1),(1,2)),
((2,0),(2,1),(2,2)),
((0,0),(1,0),(2,0)),
((0,1),(1,1),(2,1)),
((0,2),(1,2),(2,2)),
((0,0),(1,1),(2,2)),
((2,0),(1,1),(0,2))
]
for possibility in possibilities
{
let (p1,p2,p3) = possibility
let value1 = grid[p1.0][p1.1]
let value2 = grid[p2.0][p2.1]
let value3 = grid[p3.0][p3.1]
if value1 == value2 && value2 == value3
{
if value1 != 0
{
//winner
if value1 == 1
{
gameStatusLabel.text = "Player \(value1) wins"
player1Score++
player1ScoreLabel.text = "Player 1 Score = \(player1Score)"
}
else if value1 == 2
{
gameStatusLabel.text = "Player \(value1) wins"
player2Score++
player2ScoreLabel.text = "Player 2 Score = \(player2Score)"
}
}
}
else
{
if value1 != 0 && value2 != 0 && value3 != 0
{
stalemateCount++
}
}
}
if stalemateCount >= 7
{
stalemateScore++
stalemateScoreLabel.text = "Stalemate = \(stalemateScore)"
gameStatusLabel.text = "Stalemate"
}
}
}
class TTTButton: UIButton
{
var row = 0
var col = 0
var player = 0 {
didSet {
switch player {
case 1: backgroundColor = UIColor.magentaColor()
case 2: backgroundColor = UIColor.yellowColor()
default: backgroundColor = UIColor.cyanColor()
}
}
}
func getRandomColor() -> UIColor
{
let randomRed:CGFloat = CGFloat(drand48())
let randomGreen:CGFloat = CGFloat(drand48())
let randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
}
| 4e8d314a66755b98c8c2acbeab0321cb | 28.886364 | 161 | 0.459738 | false | false | false | false |
mgsergio/omim | refs/heads/master | iphone/Maps/Classes/Components/ExpandableTextView/ExpandableTextView.swift | apache-2.0 | 1 | import UIKit
@IBDesignable final class ExpandableTextView: UIView {
@IBInspectable var text: String = "" {
didSet {
guard oldValue != text else { return }
update()
}
}
@IBInspectable var textColor: UIColor? {
get { return settings.textColor }
set {
settings.textColor = newValue ?? settings.textColor
update()
}
}
@IBInspectable var expandText: String {
get { return settings.expandText }
set {
settings.expandText = newValue
update()
}
}
@IBInspectable var expandTextColor: UIColor? {
get { return settings.expandTextColor }
set {
settings.expandTextColor = newValue ?? settings.expandTextColor
update()
}
}
@IBInspectable var numberOfCompactLines: Int {
get { return settings.numberOfCompactLines }
set {
settings.numberOfCompactLines = newValue
update()
}
}
var textFont: UIFont {
get { return settings.textFont }
set {
settings.textFont = newValue
update()
}
}
var settings = ExpandableTextViewSettings() {
didSet { update() }
}
var onUpdate: (() -> Void)?
override var frame: CGRect {
didSet {
guard frame.size != oldValue.size else { return }
update()
}
}
override var bounds: CGRect {
didSet {
guard bounds.size != oldValue.size else { return }
update()
}
}
private var isCompact = true {
didSet {
guard oldValue != isCompact else { return }
update()
}
}
private func createTextLayer() -> CALayer {
let size: CGSize
let container = CALayer()
container.anchorPoint = CGPoint()
container.contentsScale = UIScreen.main.scale
if isCompact {
size = text.size(width: frame.width, font: textFont, maxNumberOfLines: numberOfCompactLines)
let fullSize = text.size(width: frame.width, font: textFont, maxNumberOfLines: 0)
if size.height < fullSize.height {
let expandSize = expandText.size(width: frame.width, font: textFont, maxNumberOfLines: 1)
let layer = CATextLayer()
layer.position = CGPoint(x: 0, y: size.height)
layer.bounds = CGRect(origin: CGPoint(), size: expandSize)
layer.anchorPoint = CGPoint()
layer.string = expandText
layer.font = CGFont(textFont.fontName as CFString)
layer.fontSize = textFont.pointSize
layer.foregroundColor = expandTextColor?.cgColor
layer.contentsScale = UIScreen.main.scale
container.addSublayer(layer)
}
} else {
size = text.size(width: frame.width, font: textFont, maxNumberOfLines: 0)
}
let layer = CATextLayer()
layer.bounds = CGRect(origin: CGPoint(), size: size)
layer.anchorPoint = CGPoint()
layer.string = text
layer.isWrapped = true
layer.truncationMode = kCATruncationEnd
layer.font = CGFont(textFont.fontName as CFString)
layer.fontSize = textFont.pointSize
layer.foregroundColor = textColor?.cgColor
layer.contentsScale = UIScreen.main.scale
container.addSublayer(layer)
var containerSize = CGSize()
container.sublayers?.forEach { layer in
containerSize.width = max(containerSize.width, layer.frame.maxX)
containerSize.height = max(containerSize.height, layer.frame.maxY)
}
container.frame.size = containerSize
return container
}
public override func awakeFromNib() {
super.awakeFromNib()
setup()
}
public convenience init() {
self.init(frame: CGRect())
}
public override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
layer.backgroundColor = UIColor.clear.cgColor
isOpaque = true
gestureRecognizers = nil
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(onTap)))
update()
}
private var viewSize = CGSize()
private func updateImpl() {
let sublayer = createTextLayer()
layer.sublayers = [sublayer]
viewSize = sublayer.bounds.size
invalidateIntrinsicContentSize()
onUpdate?()
}
@objc private func doUpdate() {
DispatchQueue.main.async {
self.updateImpl()
}
}
func update() {
let sel = #selector(doUpdate)
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: sel, object: nil)
perform(sel, with: nil, afterDelay: 1 / 120)
}
override var intrinsicContentSize: CGSize {
return viewSize
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
updateImpl()
}
@objc private func onTap() {
isCompact = false
}
}
| d2f68bc560cd37bec7e76f6ad751ce56 | 23.721053 | 98 | 0.657654 | false | false | false | false |
joerocca/GitHawk | refs/heads/master | Local Pods/SwipeCellKit/Source/SwipeCollectionViewCell+Display.swift | mit | 2 | //
// SwipeCollectionViewCell+Display.swift
//
// Created by Jeremy Koch
// Copyright © 2017 Jeremy Koch. All rights reserved.
//
import UIKit
extension SwipeCollectionViewCell {
/// The point at which the origin of the cell is offset from the non-swiped origin.
public var swipeOffset: CGFloat {
set { setSwipeOffset(newValue, animated: false) }
get { return frame.midX - bounds.midX }
}
/**
Hides the swipe actions and returns the cell to center.
- parameter animated: Specify `true` to animate the hiding of the swipe actions or `false` to hide it immediately.
- parameter completion: The closure to be executed once the animation has finished. A `Boolean` argument indicates whether or not the animations actually finished before the completion handler was called.
*/
public func hideSwipe(animated: Bool, completion: ((Bool) -> Void)? = nil) {
guard state == .left || state == .right else { return }
state = .animatingToCenter
collectionView?.setGestureEnabled(true)
let targetCenter = self.targetCenter(active: false)
if animated {
animate(toOffset: targetCenter) { complete in
self.reset()
completion?(complete)
}
} else {
center = CGPoint(x: targetCenter, y: self.center.y)
reset()
}
notifyEditingStateChange(active: false)
}
/**
Shows the swipe actions for the specified orientation.
- parameter orientation: The side of the cell on which to show the swipe actions.
- parameter animated: Specify `true` to animate the showing of the swipe actions or `false` to show them immediately.
- parameter completion: The closure to be executed once the animation has finished. A `Boolean` argument indicates whether or not the animations actually finished before the completion handler was called.
*/
public func showSwipe(orientation: SwipeActionsOrientation, animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
setSwipeOffset(.greatestFiniteMagnitude * -orientation.scale,
animated: animated,
completion: completion)
}
/**
The point at which the origin of the cell is offset from the non-swiped origin.
- parameter offset: A point (expressed in points) that is offset from the non-swiped origin.
- parameter animated: Specify `true` to animate the transition to the new offset, `false` to make the transition immediate.
- parameter completion: The closure to be executed once the animation has finished. A `Boolean` argument indicates whether or not the animations actually finished before the completion handler was called.
*/
public func setSwipeOffset(_ offset: CGFloat, animated: Bool = true, completion: ((Bool) -> Void)? = nil) {
guard offset != 0 else {
hideSwipe(animated: animated, completion: completion)
return
}
let orientation: SwipeActionsOrientation = offset > 0 ? .left : .right
let targetState = SwipeState(orientation: orientation)
if state != targetState {
guard showActionsView(for: orientation) else { return }
collectionView?.hideSwipeCell()
state = targetState
}
let maxOffset = min(bounds.width, abs(offset)) * -orientation.scale
let targetCenter = abs(offset) == CGFloat.greatestFiniteMagnitude ? self.targetCenter(active: true) : bounds.midX + maxOffset
if animated {
animate(toOffset: targetCenter) { complete in
completion?(complete)
}
} else {
center.x = targetCenter
}
}
}
| 0e5e064084a2206ad9b3fa68b0a4c8bb | 37.510204 | 209 | 0.654743 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/MediaPackageVod/MediaPackageVod_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for MediaPackageVod
public struct MediaPackageVodErrorType: AWSErrorType {
enum Code: String {
case forbiddenException = "ForbiddenException"
case internalServerErrorException = "InternalServerErrorException"
case notFoundException = "NotFoundException"
case serviceUnavailableException = "ServiceUnavailableException"
case tooManyRequestsException = "TooManyRequestsException"
case unprocessableEntityException = "UnprocessableEntityException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize MediaPackageVod
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
public static var forbiddenException: Self { .init(.forbiddenException) }
public static var internalServerErrorException: Self { .init(.internalServerErrorException) }
public static var notFoundException: Self { .init(.notFoundException) }
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
public static var unprocessableEntityException: Self { .init(.unprocessableEntityException) }
}
extension MediaPackageVodErrorType: Equatable {
public static func == (lhs: MediaPackageVodErrorType, rhs: MediaPackageVodErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension MediaPackageVodErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 646252e39e48d34569deaa8fead4b41d | 37.227273 | 117 | 0.680539 | false | false | false | false |
manavgabhawala/swift | refs/heads/master | test/SILOptimizer/definite_init_failable_initializers.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-sil -disable-objc-attr-requires-foundation-module %s | %FileCheck %s
// High-level tests that DI handles early returns from failable and throwing
// initializers properly. The main complication is conditional release of self
// and stored properties.
// FIXME: not all of the test cases have CHECKs. Hopefully the interesting cases
// are fully covered, though.
////
// Structs with failable initializers
////
protocol Pachyderm {
init()
}
class Canary : Pachyderm {
required init() {}
}
// <rdar://problem/20941576> SILGen crash: Failable struct init cannot delegate to another failable initializer
struct TrivialFailableStruct {
init?(blah: ()) { }
init?(wibble: ()) {
self.init(blah: wibble)
}
}
struct FailableStruct {
let x, y: Canary
init(noFail: ()) {
x = Canary()
y = Canary()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt24failBeforeInitialization_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[SELF]]
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt30failAfterPartialInitialization_tcfC
// CHECK: bb0(%0 : $@thin FailableStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: store [[CANARY]] to [[X_ADDR]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: strong_release [[CANARY]]
// CHECK-NEXT: [[SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[SELF]]
init?(failAfterPartialInitialization: ()) {
x = Canary()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt27failAfterFullInitialization_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY1:%.*]] = apply
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: store [[CANARY1]] to [[X_ADDR]]
// CHECK: [[CANARY2:%.*]] = apply
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: store [[CANARY2]] to [[Y_ADDR]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[SELF:%.*]] = struct $FailableStruct ([[CANARY1]] : $Canary, [[CANARY2]] : $Canary)
// CHECK-NEXT: release_value [[SELF]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
x = Canary()
y = Canary()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt46failAfterWholeObjectInitializationByAssignment_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[CANARY]] = apply
// CHECK-NEXT: store [[CANARY]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: release_value [[CANARY]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[SELF_VALUE]]
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableStruct(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt46failAfterWholeObjectInitializationByDelegation_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers14FailableStructVACSgyt20failDuringDelegation_tcfC
// CHECK: bb0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14FailableStructVACSgyt24failBeforeInitialization_tcfC
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], bb1, bb2
// CHECK: bb1:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableStruct>)
// CHECK: bb2:
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableStruct>)
// CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableStruct>)
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
init!(failDuringDelegation3: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation4: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation5: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableStruct {
init?(failInExtension: ()) {
self.init(failInExtension: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableStruct(noFail: ())
}
}
struct FailableAddrOnlyStruct<T : Pachyderm> {
var x, y: T
init(noFail: ()) {
x = T()
y = T()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failBeforeInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: br bb1
// CHECK: bb1:
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return
init?(failBeforeInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterPartialInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: destroy_addr [[X_ADDR]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return
init?(failAfterPartialInitialization: ()) {
x = T()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers22FailableAddrOnlyStructV{{[_0-9a-zA-Z]*}}failAfterFullInitialization{{.*}}tcfC
// CHECK: bb0(%0 : $*Optional<FailableAddrOnlyStruct<T>>, %1 : $@thin FailableAddrOnlyStruct<T>.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableAddrOnlyStruct<T>
// CHECK: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: [[X_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[X_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[X_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: copy_addr [take] [[X_BOX]] to [initialization] [[X_ADDR]]
// CHECK-NEXT: dealloc_stack [[X_BOX]]
// CHECK-NEXT: [[T_INIT_FN:%.*]] = witness_method $T, #Pachyderm.init!allocator.1
// CHECK-NEXT: [[Y_BOX:%.*]] = alloc_stack $T
// CHECK-NEXT: [[T_TYPE:%.*]] = metatype $@thick T.Type
// CHECK-NEXT: apply [[T_INIT_FN]]<T>([[Y_BOX]], [[T_TYPE]])
// CHECK-NEXT: [[Y_ADDR:%.*]] = struct_element_addr [[SELF_BOX]]
// CHECK-NEXT: copy_addr [take] [[Y_BOX]] to [initialization] [[Y_ADDR]]
// CHECK-NEXT: dealloc_stack [[Y_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: inject_enum_addr %0
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return
init?(failAfterFullInitialization: ()) {
x = T()
y = T()
return nil
}
init?(failAfterWholeObjectInitializationByAssignment: ()) {
self = FailableAddrOnlyStruct(noFail: ())
return nil
}
init?(failAfterWholeObjectInitializationByDelegation: ()) {
self.init(noFail: ())
return nil
}
// Optional to optional
init?(failDuringDelegation: ()) {
self.init(failBeforeInitialization: ())
}
// IUO to optional
init!(failDuringDelegation2: ()) {
self.init(failBeforeInitialization: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
init(failDuringDelegation3: ()) {
self.init(failBeforeInitialization: ())! // necessary '!'
}
// non-optional to IUO
init(failDuringDelegation4: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
}
extension FailableAddrOnlyStruct {
init?(failInExtension: ()) {
self.init(failBeforeInitialization: failInExtension)
}
init?(assignInExtension: ()) {
self = FailableAddrOnlyStruct(noFail: ())
}
}
////
// Structs with throwing initializers
////
func unwrap(_ x: Int) throws -> Int { return x }
struct ThrowStruct {
var x: Canary
init(fail: ()) throws { x = Canary() }
init(noFail: ()) { x = Canary() }
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi20failBeforeDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi28failBeforeOrDuringDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi29failBeforeOrDuringDelegation2_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACSi20failBeforeDelegation_tKcfC
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: try_apply [[INIT_FN]]([[RESULT]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi20failDuringDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi19failAfterDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK: release_value [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi27failDuringOrAfterDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:.*]] : $ThrowStruct):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi27failBeforeOrAfterDelegation_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSgSi16throwsToOptional_tcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACSi20failDuringDelegation_tKcfC
// CHECK-NEXT: try_apply [[INIT_FN]](%0, %1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[NEW_SELF]]
// CHECK-NEXT: br bb2([[SELF_OPTIONAL]] : $Optional<ThrowStruct>)
// CHECK: bb2([[SELF_OPTIONAL:%.*]] : $Optional<ThrowStruct>):
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], bb3, bb4
// CHECK: bb3:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: br bb5([[NEW_SELF]] : $Optional<ThrowStruct>)
// CHECK: bb4:
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb5([[NEW_SELF]] : $Optional<ThrowStruct>)
// CHECK: bb5([[NEW_SELF:%.*]] : $Optional<ThrowStruct>):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<ThrowStruct>
// CHECK: bb6:
// CHECK-NEXT: strong_release [[ERROR:%.*]] : $Error
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<ThrowStruct>, #Optional.none!enumelt
// CHECK-NEXT: br bb2([[NEW_SELF]] : $Optional<ThrowStruct>)
// CHECK: bb7([[ERROR]] : $Error):
// CHECK-NEXT: br bb6
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsToOptionalThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowStruct(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi25failDuringSelfReplacement_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt4fail_tKcfC
// CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
// CHECK-NEXT: try_apply [[INIT_FN]]([[SELF_TYPE]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowStruct):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failDuringSelfReplacement: Int) throws {
try self = ThrowStruct(fail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers11ThrowStructVACSi24failAfterSelfReplacement_tKcfC
// CHECK: bb0(%0 : $Int, %1 : $@thin ThrowStruct.Type):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowStruct
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers11ThrowStructVACyt6noFail_tcfC
// CHECK-NEXT: [[SELF_TYPE:%.*]] = metatype $@thin ThrowStruct.Type
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[SELF_TYPE]])
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: release_value [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterSelfReplacement: Int) throws {
self = ThrowStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
try self = ThrowStruct(fail: ())
}
}
struct ThrowAddrOnlyStruct<T : Pachyderm> {
var x : T
init(fail: ()) throws { x = T() }
init(noFail: ()) { x = T() }
init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init(fail: ())
}
init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
init(failDuringDelegation: Int) throws {
try self.init(fail: ())
}
init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
init(failDuringOrAfterDelegation: Int) throws {
try self.init(fail: ())
try unwrap(failDuringOrAfterDelegation)
}
init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
init?(throwsToOptional: Int) {
try? self.init(failDuringDelegation: throwsToOptional)
}
init(throwsToIUO: Int) {
try! self.init(failDuringDelegation: throwsToIUO)
}
init?(throwsToOptionalThrows: Int) throws {
try? self.init(fail: ())
}
init(throwsOptionalToThrows: Int) throws {
self.init(throwsToOptional: throwsOptionalToThrows)!
}
init?(throwsOptionalToOptional: Int) {
try! self.init(throwsOptionalToThrows: throwsOptionalToOptional)
}
init(failBeforeSelfReplacement: Int) throws {
try unwrap(failBeforeSelfReplacement)
self = ThrowAddrOnlyStruct(noFail: ())
}
init(failAfterSelfReplacement: Int) throws {
self = ThrowAddrOnlyStruct(noFail: ())
try unwrap(failAfterSelfReplacement)
}
}
extension ThrowAddrOnlyStruct {
init(failInExtension: ()) throws {
try self.init(fail: failInExtension)
}
init(assignInExtension: ()) throws {
self = ThrowAddrOnlyStruct(noFail: ())
}
}
////
// Classes with failable initializers
////
class FailableBaseClass {
var member: Canary
init(noFail: ()) {
member = Canary()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt28failBeforeFullInitialization_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[METATYPE:%.*]] = metatype $@thick FailableBaseClass.Type
// CHECK: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]]
// CHECK: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK: return [[RESULT]]
init?(failBeforeFullInitialization: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt27failAfterFullInitialization_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: store [[CANARY]] to [[MEMBER_ADDR]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: strong_release %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: return [[NEW_SELF]]
init?(failAfterFullInitialization: ()) {
member = Canary()
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt20failBeforeDelegation_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick FailableBaseClass.Type, %0 : $FailableBaseClass
// CHECK-NEXT: dealloc_partial_ref %0 : $FailableBaseClass, [[METATYPE]] : $@thick FailableBaseClass.Type
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[RESULT]]
convenience init?(failBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt19failAfterDelegation_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%0)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[RESULT]]
convenience init?(failAfterDelegation: ()) {
self.init(noFail: ())
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt20failDuringDelegation_tcfc
// CHECK: bb0(%0 : $FailableBaseClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableBaseClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = class_method %0
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]](%0)
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], bb1, bb2
// CHECK: bb1:
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableBaseClass>)
// CHECK: bb2:
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableBaseClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableBaseClass>)
// CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableBaseClass>):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// Optional to optional
convenience init?(failDuringDelegation: ()) {
self.init(failBeforeFullInitialization: ())
}
// IUO to optional
convenience init!(failDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // unnecessary-but-correct '!'
}
// IUO to IUO
convenience init!(noFailDuringDelegation: ()) {
self.init(failDuringDelegation2: ())! // unnecessary-but-correct '!'
}
// non-optional to optional
convenience init(noFailDuringDelegation2: ()) {
self.init(failBeforeFullInitialization: ())! // necessary '!'
}
}
extension FailableBaseClass {
convenience init?(failInExtension: ()) throws {
self.init(failBeforeFullInitialization: failInExtension)
}
}
// Chaining to failable initializers in a superclass
class FailableDerivedClass : FailableBaseClass {
var otherMember: Canary
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassCACSgyt27derivedFailBeforeDelegation_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: br bb1
// CHECK: bb1:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick FailableDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %0 : $FailableDerivedClass, [[METATYPE]] : $@thick FailableDerivedClass.Type
// CHECK-NEXT: [[RESULT:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[RESULT]]
init?(derivedFailBeforeDelegation: ()) {
return nil
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers20FailableDerivedClassCACSgyt27derivedFailDuringDelegation_tcfc
// CHECK: bb0(%0 : $FailableDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $FailableDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK: [[CANARY:%.*]] = apply
// CHECK-NEXT: [[MEMBER_ADDR:%.*]] = ref_element_addr %0
// CHECK-NEXT: store [[CANARY]] to [[MEMBER_ADDR]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17FailableBaseClassCACSgyt28failBeforeFullInitialization_tcfc
// CHECK-NEXT: [[SELF_OPTIONAL:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: [[COND:%.*]] = select_enum [[SELF_OPTIONAL]]
// CHECK-NEXT: cond_br [[COND]], bb1, bb2
// CHECK: bb1:
// CHECK-NEXT: [[BASE_SELF_VALUE:%.*]] = unchecked_enum_data [[SELF_OPTIONAL]]
// CHECK-NEXT: [[SELF_VALUE:%.*]] = unchecked_ref_cast [[BASE_SELF_VALUE]]
// CHECK-NEXT: store [[SELF_VALUE]] to [[SELF_BOX]]
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.some!enumelt.1, [[SELF_VALUE]]
// CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableDerivedClass>)
// CHECK: bb2:
// CHECK-NEXT: [[NEW_SELF:%.*]] = enum $Optional<FailableDerivedClass>, #Optional.none!enumelt
// CHECK-NEXT: br bb3([[NEW_SELF]] : $Optional<FailableDerivedClass>)
// CHECK: bb3([[NEW_SELF:%.*]] : $Optional<FailableDerivedClass>):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]] : $Optional<FailableDerivedClass>
init?(derivedFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failBeforeFullInitialization: ())
}
init?(derivedFailAfterDelegation: ()) {
self.otherMember = Canary()
super.init(noFail: ())
return nil
}
// non-optional to IUO
init(derivedNoFailDuringDelegation: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // necessary '!'
}
// IUO to IUO
init!(derivedFailDuringDelegation2: ()) {
self.otherMember = Canary()
super.init(failAfterFullInitialization: ())! // unnecessary-but-correct '!'
}
}
extension FailableDerivedClass {
convenience init?(derivedFailInExtension: ()) throws {
self.init(derivedFailDuringDelegation: derivedFailInExtension)
}
}
////
// Classes with throwing initializers
////
class ThrowBaseClass {
required init() throws {}
init(noFail: ()) {}
}
class ThrowDerivedClass : ThrowBaseClass {
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK: bb0(%0 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %0 to [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %0
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
required init() throws {
try super.init()
}
override init(noFail: ()) {
try! super.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]] : $ThrowDerivedClass
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h6DuringjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]] : $*ThrowDerivedClass
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int)
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref %2 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failAfterFullInitialization_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %1
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[DERIVED_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int) throws {
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failAfterFullInitialization_Si0h6DuringjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[DERIVED_SELF]])
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failAfterFullInitialization: Int, failDuringFullInitialization: Int) throws {
try super.init()
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h5AfterjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %2 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %2
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyt6noFail_tcfc
// CHECK: [[NEW_SELF:%.*]] = apply [[INIT_FN]]([[BASE_SELF]])
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%1)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND:%.*]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[BITMAP:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[BITMAP]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
init(failBeforeFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
super.init(noFail: ())
try unwrap(failAfterFullInitialization)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeFullInitialization_Si0h6DuringjK0Si0h5AfterjK0tKcfc
// CHECK: bb0(%0 : $Int, %1 : $Int, %2 : $Int, %3 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %3 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast %3
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers14ThrowBaseClassCACyKcfc
// CHECK: try_apply [[INIT_FN]]([[BASE_SELF]])
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowBaseClass):
// CHECK-NEXT: [[DERIVED_SELF:%.*]] = unchecked_ref_cast [[NEW_SELF]]
// CHECK-NEXT: store [[DERIVED_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%2)
// CHECK: bb3([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[DERIVED_SELF]]
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb7([[ERROR]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb8, bb9
// CHECK: bb8:
// CHECK-NEXT: br bb13
// CHECK: bb9:
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb10, bb11
// CHECK: bb10:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb12
// CHECK: bb11:
// CHECK-NEXT: [[SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_partial_ref [[SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb12
// CHECK: bb12:
// CHECK-NEXT: br bb13
// CHECK: bb13:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
init(failBeforeFullInitialization: Int, failDuringFullInitialization: Int, failAfterFullInitialization: Int) throws {
try unwrap(failBeforeFullInitialization)
try super.init()
try unwrap(failAfterFullInitialization)
}
convenience init(noFail2: ()) {
try! self.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failBeforeDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeDelegation: Int) throws {
try unwrap(failBeforeDelegation)
self.init(noFail: ())
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failDuringDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]] : $Error
convenience init(failDuringDelegation: Int) throws {
try self.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi28failBeforeOrDuringDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2)
// CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failBeforeOrDuringDelegation: Int) throws {
try unwrap(failBeforeOrDuringDelegation)
try self.init()
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi29failBeforeOrDuringDelegation2_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]] : $*Builtin.Int2
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[ARG:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi20failBeforeDelegation_tKcfc
// CHECK-NEXT: try_apply [[INIT_FN]]([[ARG]], %1)
// CHECK: bb2([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: store %1 to [[SELF_BOX]]
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb5([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP_VALUE:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[BIT_NUM:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP_VALUE]] : $Builtin.Int2, [[BIT_NUM]] : $Builtin.Int2)
// CHECK-NEXT: [[CONDITION:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[CONDITION]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, %1 : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref %1 : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR2]]
convenience init(failBeforeOrDuringDelegation2: Int) throws {
try self.init(failBeforeDelegation: unwrap(failBeforeOrDuringDelegation2))
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi19failAfterDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: strong_release [[NEW_SELF]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failAfterDelegation: Int) throws {
self.init(noFail: ())
try unwrap(failAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failDuringOrAfterDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int2
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK: [[ZERO:%.*]] = integer_literal $Builtin.Int2, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %1 to [[SELF_BOX]]
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyKcfc
// CHECK-NEXT: try_apply [[INIT_FN]](%1)
// CHECK: bb1([[NEW_SELF:%.*]] : $ThrowDerivedClass):
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR1:%.*]] : $Error):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int2, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK-NEXT: br bb5([[ERROR1]] : $Error)
// CHECK: bb4([[ERROR2:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR2]] : $Error)
// CHECK: bb5([[ERROR3:%.*]] : $Error):
// CHECK-NEXT: [[BITMAP:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: [[ONE:%.*]] = integer_literal $Builtin.Int2, 1
// CHECK-NEXT: [[BITMAP_MSB:%.*]] = builtin "lshr_Int2"([[BITMAP]] : $Builtin.Int2, [[ONE]] : $Builtin.Int2)
// CHECK-NEXT: [[COND:%.*]] = builtin "trunc_Int2_Int1"([[BITMAP_MSB]] : $Builtin.Int2)
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR3]]
convenience init(failDuringOrAfterDelegation: Int) throws {
try self.init()
try unwrap(failDuringOrAfterDelegation)
}
// CHECK-LABEL: sil hidden @_T035definite_init_failable_initializers17ThrowDerivedClassCACSi27failBeforeOrAfterDelegation_tKcfc
// CHECK: bb0(%0 : $Int, %1 : $ThrowDerivedClass):
// CHECK-NEXT: [[BITMAP_BOX:%.*]] = alloc_stack $Builtin.Int1
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $ThrowDerivedClass
// CHECK-NEXT: [[ZERO:%.*]] = integer_literal $Builtin.Int1, 0
// CHECK-NEXT: store [[ZERO]] to [[BITMAP_BOX]]
// CHECK: store %1 to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb1([[RESULT:%.*]] : $Int):
// CHECK-NEXT: [[BIT:%.*]] = integer_literal $Builtin.Int1, -1
// CHECK-NEXT: store [[BIT]] to [[BITMAP_BOX]]
// CHECK: [[INIT_FN:%.*]] = function_ref @_T035definite_init_failable_initializers17ThrowDerivedClassCACyt6noFail_tcfc
// CHECK-NEXT: [[NEW_SELF:%.*]] = apply [[INIT_FN]](%1)
// CHECK-NEXT: store [[NEW_SELF]] to [[SELF_BOX]]
// CHECK: [[UNWRAP_FN:%.*]] = function_ref @_T035definite_init_failable_initializers6unwrapS2iKF
// CHECK-NEXT: try_apply [[UNWRAP_FN]](%0)
// CHECK: bb2([[RESULT:%.*]] : $Int):
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: return [[NEW_SELF]]
// CHECK: bb3([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb4([[ERROR:%.*]] : $Error):
// CHECK-NEXT: br bb5([[ERROR]] : $Error)
// CHECK: bb5([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[COND:%.*]] = load [[BITMAP_BOX]]
// CHECK-NEXT: cond_br [[COND]], bb6, bb7
// CHECK: bb6:
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: br bb8
// CHECK: bb7:
// CHECK-NEXT: [[OLD_SELF:%.*]] = load [[SELF_BOX]]
// CHECK-NEXT: [[METATYPE:%.*]] = value_metatype $@thick ThrowDerivedClass.Type, [[OLD_SELF]] : $ThrowDerivedClass
// CHECK-NEXT: dealloc_partial_ref [[OLD_SELF]] : $ThrowDerivedClass, [[METATYPE]] : $@thick ThrowDerivedClass.Type
// CHECK-NEXT: br bb8
// CHECK: bb8:
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[BITMAP_BOX]]
// CHECK-NEXT: throw [[ERROR]]
convenience init(failBeforeOrAfterDelegation: Int) throws {
try unwrap(failBeforeOrAfterDelegation)
self.init(noFail: ())
try unwrap(failBeforeOrAfterDelegation)
}
}
////
// Enums with failable initializers
////
enum FailableEnum {
case A
init?(a: Int64) { self = .A }
init!(b: Int64) {
self.init(a: b)! // unnecessary-but-correct '!'
}
init(c: Int64) {
self.init(a: c)! // necessary '!'
}
init(d: Int64) {
self.init(b: d)! // unnecessary-but-correct '!'
}
}
////
// Protocols and protocol extensions
////
// Delegating to failable initializers from a protocol extension to a
// protocol.
protocol P1 {
init?(p1: Int64)
}
extension P1 {
init!(p1a: Int64) {
self.init(p1: p1a)! // unnecessary-but-correct '!'
}
init(p1b: Int64) {
self.init(p1: p1b)! // necessary '!'
}
}
protocol P2 : class {
init?(p2: Int64)
}
extension P2 {
init!(p2a: Int64) {
self.init(p2: p2a)! // unnecessary-but-correct '!'
}
init(p2b: Int64) {
self.init(p2: p2b)! // necessary '!'
}
}
@objc protocol P3 {
init?(p3: Int64)
}
extension P3 {
init!(p3a: Int64) {
self.init(p3: p3a)! // unnecessary-but-correct '!'
}
init(p3b: Int64) {
self.init(p3: p3b)! // necessary '!'
}
}
// Delegating to failable initializers from a protocol extension to a
// protocol extension.
extension P1 {
init?(p1c: Int64) {
self.init(p1: p1c)
}
init!(p1d: Int64) {
self.init(p1c: p1d)! // unnecessary-but-correct '!'
}
init(p1e: Int64) {
self.init(p1c: p1e)! // necessary '!'
}
}
extension P2 {
init?(p2c: Int64) {
self.init(p2: p2c)
}
init!(p2d: Int64) {
self.init(p2c: p2d)! // unnecessary-but-correct '!'
}
init(p2e: Int64) {
self.init(p2c: p2e)! // necessary '!'
}
}
////
// type(of: self) with uninitialized self
////
func use(_ a : Any) {}
class DynamicTypeBase {
var x: Int
init() {
use(type(of: self))
x = 0
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
class DynamicTypeDerived : DynamicTypeBase {
override init() {
use(type(of: self))
super.init()
}
convenience init(a : Int) {
use(type(of: self))
self.init()
}
}
struct DynamicTypeStruct {
var x: Int
init() {
use(type(of: self))
x = 0
}
init(a : Int) {
use(type(of: self))
self.init()
}
}
| 8e8525e6b3446d6a6ca1a30639acc6a5 | 41.301741 | 155 | 0.621658 | false | false | false | false |
pavelpark/RoundMedia | refs/heads/master | roundMedia/roundMedia/CleanButton.swift | mit | 1 | //
// CleanButton.swift
// roundMedia
//
// Created by Pavel Parkhomey on 7/16/17.
// Copyright © 2017 Pavel Parkhomey. All rights reserved.
//
import UIKit
class CleanButton: UIButton {
override func awakeFromNib() {
super.awakeFromNib()
layer.shadowColor = UIColor(red: SHADOW_GRAY, green: SHADOW_GRAY, blue: SHADOW_GRAY, alpha: 0.6).cgColor
layer.shadowOpacity = 0.8
layer.shadowRadius = 5.0
layer.shadowOffset = CGSize(width: 1.0, height: 1.0)
layer.cornerRadius = 2.0
}
}
| e337e0292076a212e0c802e79a0bc6ed | 21.458333 | 108 | 0.651206 | false | false | false | false |
manavgabhawala/swift | refs/heads/master | test/DebugInfo/linetable.swift | apache-2.0 | 1 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -emit-ir -g -o - | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests %s -S -g -o - | %FileCheck %s --check-prefix ASM-CHECK
// REQUIRES: CPU=i386_or_x86_64
import Swift
func markUsed<T>(_ t: T) {}
class MyClass
{
var x : Int64
init(input: Int64) { x = input }
func do_something(_ input: Int64) -> Int64
{
return x * input
}
}
func call_me(_ code: @escaping () -> Void)
{
code ()
}
func main(_ x: Int64) -> Void
// CHECK: define hidden {{.*}} void @_T09linetable4main{{[_0-9a-zA-Z]*}}F
{
var my_class = MyClass(input: 10)
// Linetable continuity. Don't go into the closure expression.
// ASM-CHECK: .loc [[FILEID:[0-9]]] [[@LINE+1]] 5
call_me (
// ASM-CHECK-NOT: .loc [[FILEID]] [[@LINE+1]] 5
// CHECK: define {{.*}} @_T09linetable4mainys5Int64VFyycfU_Tf2in_n({{.*}})
{
var result = my_class.do_something(x)
markUsed(result)
// CHECK: call {{.*}} @swift_rt_swift_release {{.*}}
// CHECK: call {{.*}} @swift_rt_swift_release {{.*}}, !dbg ![[CLOSURE_END:.*]]
// CHECK-NEXT: bitcast
// CHECK-NEXT: llvm.lifetime.end
// CHECK-NEXT: ret void, !dbg ![[CLOSURE_END]]
// CHECK: ![[CLOSURE_END]] = !DILocation(line: [[@LINE+1]],
}
)
// The swift_releases at the end should not jump to the point where
// that memory was retained/allocated and also not to line 0.
// ASM-CHECK-NOT: .loc [[FILEID]] 0 0
// ASM-CHECK: .loc [[FILEID]] [[@LINE+2]] 1
// ASM-CHECK: ret
}
// ASM-CHECK: {{^_?_T09linetable4mainys5Int64VFyycfU_Tf2in_n:}}
// ASM-CHECK-NOT: retq
// The end-of-prologue should have a valid location (0 is ok, too).
// ASM-CHECK: .loc [[FILEID]] 0 {{[0-9]+}} prologue_end
// ASM-CHECK: .loc [[FILEID]] 34 {{[0-9]+}}
main(30)
| 4285077735dfbbe57bccee4aee0340cc | 30.068966 | 116 | 0.600999 | false | false | false | false |
siemensikkema/Fairness | refs/heads/master | FairnessTests/TransactionCalculatorTests.swift | mit | 1 | import XCTest
class TransactionCalculatorTests: XCTestCase {
class ParticipantTransactionModelForTesting: ParticipantTransactionModel {
var didCallReset = false
init() {
super.init(participant: Participant(name: ""))
}
override func reset() {
didCallReset = true
}
}
var sut: TransactionCalculator!
var notificationCenter: FairnessNotificationCenterForTesting!
var participantTransactionModels: [ParticipantTransactionModelForTesting]!
override func setUp() {
notificationCenter = FairnessNotificationCenterForTesting()
participantTransactionModels = [ParticipantTransactionModelForTesting(), ParticipantTransactionModelForTesting()]
sut = TransactionCalculator(notificationCenter: notificationCenter)
sut.participantTransactionModels = participantTransactionModels
sut.togglePayerAtIndex(0)
sut.togglePayeeAtIndex(1)
sut.cost = 1.23
}
}
extension TransactionCalculatorTests {
func testNumberOfParticipantTransactionModelsEqualsNumberOfParticipants() {
XCTAssertEqual(sut.participantTransactionModels.count, 2)
}
func testHasPayerReturnsTrueWhenOneParticipantsIsPayer() {
XCTAssertTrue(sut.hasPayer)
}
func testHasPayerReturnsFalseWhenNoParticipantsArePayer() {
sut.togglePayerAtIndex(0)
XCTAssertFalse(sut.hasPayer)
}
func testTransactionWithPayerAndPayeeAndNonZeroCostIsValid() {
XCTAssertTrue(sut.isValid)
}
func testTransactionIsInvalidWithoutPayer() {
sut.togglePayerAtIndex(0)
XCTAssertFalse(sut.isValid)
}
func testTransactionIsInvalidWithoutPayee() {
sut.togglePayeeAtIndex(1)
XCTAssertFalse(sut.isValid)
}
func testTransactionIsInvalidWithZeroCost() {
sut.cost = 0
XCTAssertFalse(sut.isValid)
}
func testTransactionIsInvalidWhenPayerIsTheOnlyPayee() {
sut.togglePayeeAtIndex(0)
sut.togglePayeeAtIndex(1)
XCTAssertFalse(sut.isValid)
}
func testTransactionIsValidWhenPayerIsOneOfThePayees() {
sut.togglePayeeAtIndex(0)
XCTAssertTrue(sut.isValid)
}
func testTransactionAmountsForSimpleTransactionAreCorrect() {
XCTAssertEqual(sut.participantTransactionModels.map { $0.amountOrNil! }, [1.23, -1.23])
}
func testTransactionAmountsForSharedTransactionAreCorrect() {
sut.togglePayeeAtIndex(0)
XCTAssertEqual(sut.participantTransactionModels.map { $0.amountOrNil! }, [0.615, -0.615])
}
func testAmounts() {
XCTAssertEqual(sut.amounts, [1.23,-1.23])
}
func testResetSetsCostToZero() {
notificationCenter.transactionDidEndCallback?()
XCTAssertEqual(sut.cost, 0.0)
}
func testResetResetsParticipantViewModels() {
notificationCenter.transactionDidEndCallback?()
XCTAssertEqual(participantTransactionModels.map { $0.didCallReset }, [true, true])
}
} | bb6303fc9cd0bb5dc35f3503b5a7445f | 29.535354 | 121 | 0.70814 | false | true | false | false |
tuanquanghpvn/BeeFly | refs/heads/master | BeeFly/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// BeeFly
//
// Created by on 3/4/16.
// Copyright (c) 2016 Tuan_Quang. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| 0b7ca9698a0f970455c354585a3a86c5 | 25.396226 | 94 | 0.595425 | false | false | false | false |
elpassion/el-space-ios | refs/heads/master | ELSpaceTests/TestCases/ViewModels/ProjectSearchViewModelSpec.swift | gpl-3.0 | 1 | @testable import ELSpace
import Quick
import Nimble
import RxSwift
import RxCocoa
class ProjectSearchViewModelSpec: QuickSpec {
override func spec() {
describe("ProjectSearchViewModel") {
var projectSearchController: ProjectSearchControllerStub!
var sut: ProjectSearchViewModel!
var projectId: Int!
beforeEach {
projectId = 4
projectSearchController = ProjectSearchControllerStub()
sut = ProjectSearchViewModel(projectId: projectId, projectSearchController: projectSearchController)
}
context("when projects are supplied") {
var project1: ProjectDTO!
var project2: ProjectDTO!
var project3: ProjectDTO!
var caughtProjects: [ProjectDTO]!
beforeEach {
project1 = ProjectDTO.fakeProjectDto(name: "One", id: 1)
project2 = ProjectDTO.fakeProjectDto(name: "Two", id: 2)
project3 = ProjectDTO.fakeProjectDto(name: "Three", id: 3)
_ = sut.projects.drive(onNext: { caughtProjects = $0 })
projectSearchController.stubbedProjects.onNext([project1, project2, project3])
}
afterEach {
caughtProjects = nil
}
it("should emit all projects") {
expect(caughtProjects).to(haveCount(3))
}
context("when search text is supplied") {
context("correct capital letter text") {
beforeEach {
sut.searchText.onNext("T")
}
it("should emit filtered projects") {
expect(caughtProjects).to(haveCount(2))
expect(caughtProjects[0].id) == project2.id
expect(caughtProjects[1].id) == project3.id
}
}
context("correct lower letter text") {
beforeEach {
sut.searchText.onNext("t")
}
it("should emit filtered projects") {
expect(caughtProjects).to(haveCount(2))
expect(caughtProjects[0].id) == project2.id
expect(caughtProjects[1].id) == project3.id
}
}
context("empty text") {
beforeEach {
sut.searchText.onNext("")
}
it("should emit filtered projects") {
expect(caughtProjects).to(haveCount(3))
expect(caughtProjects[0].id) == project1.id
expect(caughtProjects[1].id) == project2.id
expect(caughtProjects[2].id) == project3.id
}
}
}
context("when project is selected") {
var caughtProject: ProjectDTO!
beforeEach {
_ = sut.didSelectProject.drive(onNext: { caughtProject = $0 })
sut.selectProject.onNext(project2)
}
it("should emit correct project") {
expect(caughtProject!.id) == project2.id
}
}
}
}
}
}
| 516d66f3e8215388a28a3ddf0dadb85f | 35.868687 | 116 | 0.453973 | false | false | false | false |
SwiftOnEdge/Edge | refs/heads/master | Sources/HTTP/Routing/ErrorEndpoint.swift | mit | 1 | //
// ErrorEndpoint.swift
// Edge
//
// Created by Tyler Fleming Cloutier on 12/18/17.
//
import Foundation
import StreamKit
import Regex
import PathToRegex
struct ErrorEndpoint: HandlerNode {
let handler: ErrorHandler
weak var parent: Router?
let method: Method?
func setParameters(on request: Request, match: Match) {
request.parameters = [:]
}
func shouldHandleAndAddParams(request: Request, error: Error) -> Bool {
if let method = method, request.method != method {
return false
}
return true
}
func handle(
requests: Signal<Request>,
errors: Signal<(Request, Error)>,
responses: Signal<Response>
) -> (
handled: Signal<Response>,
errored: Signal<(Request, Error)>,
unhandled: Signal<Request>
) {
let (shouldHandle, unhandled) = errors.partition(self.shouldHandleAndAddParams)
let (handled, errored) = handle(errors: shouldHandle)
let (mergedResponses, responsesInput) = Signal<Response>.pipe()
responses.add(observer: responsesInput)
handled.add(observer: responsesInput)
let (mergedErrored, erroredInput) = Signal<(Request, Error)>.pipe()
unhandled.add(observer: erroredInput)
errored.add(observer: erroredInput)
return (mergedResponses, mergedErrored, requests)
}
init(parent: Router? = nil, method: Method? = nil, _ handler: ErrorHandler) {
self.handler = handler
self.method = method
self.parent = parent
}
}
extension ErrorEndpoint {
func handle(errors: Signal<(Request, Error)>) -> (Signal<Response>, Signal<(Request, Error)>) {
let responses: Signal<Response>
let (newErrors, newErrorsInput) = Signal<(Request, Error)>.pipe()
switch handler {
case .sync(let syncTransform):
responses = errors.flatMap { (request, error) -> Response? in
do {
let response = try syncTransform(request, error)
response.request = request
return response
} catch {
newErrorsInput.sendNext((request, error))
return nil
}
}
case .async(let asyncTransform):
responses = errors.flatMap { (request, error) -> Signal<Response?> in
return Signal { observer in
asyncTransform(request, error).then {
$0.request = request
observer.sendNext($0)
observer.sendCompleted()
}.catch { error in
newErrorsInput.sendNext((request, error))
observer.sendNext(nil)
observer.sendCompleted()
}
return nil
}
}.flatMap { (response: Response?) in response }
}
return (responses, newErrors)
}
}
extension ErrorEndpoint: CustomStringConvertible {
var description: String {
if let method = method {
return "\(method) '\(routePath)'"
}
return "ERROR '\(routePath)'"
}
}
| e8cabee32eaf59ae4e501c5b128ed483 | 29.766355 | 99 | 0.555286 | false | false | false | false |
sdduursma/Scenic | refs/heads/master | Scenic/SceneModel.swift | mit | 1 | import Foundation
public struct SceneModel {
public var sceneName: String
public var children: [SceneModel]
public var customData: [AnyHashable: AnyHashable]?
public init(sceneName: String,
children: [SceneModel] = [],
customData: [AnyHashable: AnyHashable]? = nil) {
self.sceneName = sceneName
self.children = children
self.customData = customData
}
}
extension SceneModel: Equatable {
public static func ==(left: SceneModel, right: SceneModel) -> Bool {
return left.sceneName == right.sceneName && left.children == right.children && isCustomDataEqual(left, right)
}
private static func isCustomDataEqual(_ left: SceneModel, _ right: SceneModel) -> Bool {
if let leftCustomData = left.customData,
let rightCustomData = right.customData,
leftCustomData == rightCustomData {
return true
} else if left.customData == nil && right.customData == nil {
return true
} else {
return false
}
}
}
extension SceneModel {
public func withSceneName(_ name: String) -> SceneModel {
var new = self
new.sceneName = name
return new
}
public func withChildren(_ children: [SceneModel]) -> SceneModel {
var new = self
new.children = children
return new
}
public func withCustomData(_ customData: [AnyHashable: AnyHashable]?) -> SceneModel {
var new = self
new.customData = customData
return new
}
public func update(_ name: String, with closure: (SceneModel) -> SceneModel) -> SceneModel {
if sceneName == name {
return closure(self)
}
return withChildren(children.map { $0.update(name, with: closure)})
}
}
extension SceneModel {
public func applyTabBarDidSelectIndex(to tabBarName: String, event: NavigationEvent) -> SceneModel {
if event.eventName == TabBarScene.didSelectIndexEventName,
let index = event.customData?["selectedIndex"] as? Int {
return selectIndex(index, ofTabBar: tabBarName)
}
return self
}
public func selectIndex(_ tabBarIndex: Int, ofTabBar tabBarName: String) -> SceneModel {
return update(tabBarName) { tabBar in
var customData = tabBar.customData ?? [:]
customData["selectedIndex"] = tabBarIndex
return tabBar.withCustomData(customData)
}
}
}
extension SceneModel {
public func applyStackDidPop(to stackName: String, event: NavigationEvent) -> SceneModel {
if event.eventName == StackScene.didPopEventName,
let toIndex = event.customData?["toIndex"] as? Int {
return popStack(stackName, to: toIndex)
}
return self
}
public func popStack(_ stackName: String, to index: Int) -> SceneModel {
return update(stackName) { stack in
guard stack.children.indices.contains(index) else { return stack }
return stack.withChildren(Array(stack.children.prefix(through: index)))
}
}
}
| d07f0995c26055b90c23979a49e21c99 | 30.48 | 117 | 0.623253 | false | false | false | false |
vakoc/particle-swift-cli | refs/heads/master | Sources/WebhookCommands.swift | apache-2.0 | 1 | // This source file is part of the vakoc.com open source project(s)
//
// Copyright © 2016 Mark Vakoc. All rights reserved.
// Licensed under Apache License v2.0
//
// See http://www.vakoc.com/LICENSE.txt for license information
import Foundation
import ParticleSwift
fileprivate let productIdArgument = Argument(name: .productId, helpText: "Product ID or slug (only for product webhooks)", options: [.hasValue])
fileprivate let subHelp = "Get a list of the webhooks that you have created, either as a user or for a product."
let showWebhooksCommand = Command(name: .showWebhooks, summary: "Show Webhooks", arguments: [productIdArgument], subHelp: subHelp) {(arguments, extras, callback) in
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.webhooks(productIdOrSlug: arguments[productIdArgument]) { (result) in
switch (result) {
case .success(let webhooks):
let stringValue = "\(webhooks)"
callback( .success(string: stringValue, json: webhooks.map { $0.jsonRepresentation } ))
case .failure(let err):
callback( .failure(Errors.showWebhooksFailed(err)))
}
}
}
fileprivate let webhookIdArgument = Argument(name: .webhookId, helpText: "The webhook identifier", options: [.hasValue])
fileprivate let subHelp2 = "Get the webhook by identifier that you have created, either as a user or for a product."
let getWebhookCommand = Command(name: .getWebhook, summary: "Get Webhook", arguments: [productIdArgument, webhookIdArgument], subHelp: subHelp2) {(arguments, extras, callback) in
guard let webhookID = arguments[webhookIdArgument] else {
callback( .failure(Errors.invalidWebhookId))
return
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.webhook(webhookID, productIdOrSlug: arguments[productIdArgument]) { (result) in
switch (result) {
case .success(let webhook):
let stringValue = "\(webhook)"
callback( .success(string: stringValue, json: webhook.jsonRepresentation ))
case .failure(let err):
callback( .failure(Errors.getWebhookFailed(err)))
}
}
}
fileprivate let jsonFileArgument = Argument(name: .jsonFile, helpText: "Filename of JSON file defining the webhook relative to the current working directory", options: [.hasValue])
fileprivate let eventArgument = Argument(name: .event, helpText: "The name of the event", options: [.hasValue])
fileprivate let urlArgument = Argument(name: .url, helpText: "The name URL webhook", options: [.hasValue])
fileprivate let requestTypeArgument = Argument(name: .requestType, helpText: "The HTTP method type (GET/POST/PUT/DELETE)", options: [.hasValue])
fileprivate let subHelp3 = "Creates a webhook using either a JSON file, arguments, or a combination of both. If --event and --url arguments are specified those will be used, otherwise all parameters must come from a JSON file that includes at least those two entries. If event, url, and a JSON file are supplied the JSON file will augment the webhook definition."
// TODO: document the JSON file structure
let createWebhookCommand = Command(name: .createWebhook, summary: "Create a Webhook", arguments: [productIdArgument, jsonFileArgument, eventArgument, urlArgument, requestTypeArgument], subHelp: subHelp3) {(arguments, extras, callback) in
var webhook: Webhook?
if let event = arguments[eventArgument], let url = arguments[urlArgument], let parsedURL = URL(string: url) {
let requestType = Webhook.RequestType(rawValue: arguments[requestTypeArgument] ?? "GET")
webhook = Webhook(event: event, url: parsedURL, requestType: requestType ?? .get)
}
if let json = arguments[jsonFileArgument] {
let current = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
if let jsonUrl = URL(string: json, relativeTo: current), let data = try? Data(contentsOf: jsonUrl), let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String,Any>, let j = json {
if var hook = webhook {
hook.configure(with: j)
} else {
webhook = Webhook(with: j)
}
} else {
return callback(.failure(Errors.failedToParseJsonFile))
}
}
guard let hook = webhook else {
return callback(.failure(Errors.failedToDefinedWebhook))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.create(webhook: hook, productIdOrSlug: arguments[productIdArgument]) { result in
switch (result) {
case .success(let webhook):
let stringValue = "\(webhook)"
callback( .success(string: stringValue, json: webhook.jsonRepresentation ))
case .failure(let err):
callback( .failure(Errors.createWebhookFailed(err)))
}
}
}
fileprivate let subHelp4 = "Deletes a Webhook with the specified id"
let deleteWebhookCommand = Command(name: .deleteWebhook, summary: "Delete a Webhook", arguments: [productIdArgument,webhookIdArgument], subHelp: subHelp4) {(arguments, extras, callback) in
guard let webhookId = arguments[webhookIdArgument] else {
return callback(.failure(Errors.invalidWebhookId))
}
let particleCloud = ParticleCloud(secureStorage: CliSecureStorage.shared)
particleCloud.delete(webhookID: webhookId, productIdOrSlug: arguments[productIdArgument]) { result in
switch (result) {
case .success:
callback(.success(string: "ok", json:["ok" : true]))
case .failure(let err):
callback(.failure(Errors.deleteWebhookFailed(err)))
}
}
}
| 53df7f57ec9624b07afb90661f0896b5 | 48.728814 | 365 | 0.691036 | false | false | false | false |
Zewo/Core | refs/heads/master | Modules/Axis/Sources/Axis/Map/Map.swift | mit | 2 | public protocol MapInitializable {
init(map: Map) throws
}
public protocol MapRepresentable : MapFallibleRepresentable {
var map: Map { get }
}
public protocol MapFallibleRepresentable {
func asMap() throws -> Map
}
extension MapRepresentable {
public func asMap() throws -> Map {
return map
}
}
public protocol MapConvertible : MapInitializable, MapFallibleRepresentable {}
public enum Map {
case null
case bool(Bool)
case double(Double)
case int(Int)
case string(String)
case buffer(Buffer)
case array([Map])
case dictionary([String: Map])
}
// MARK: MapError
public enum MapError : Error {
case incompatibleType
case outOfBounds
case valueNotFound
case notMapInitializable(Any.Type)
case notMapRepresentable(Any.Type)
case notMapDictionaryKeyInitializable(Any.Type)
case notMapDictionaryKeyRepresentable(Any.Type)
case cannotInitialize(type: Any.Type, from: Any.Type)
}
// MARK: Parser/Serializer Protocols
public enum MapParserError : Error {
case invalidInput
}
public protocol MapParser {
init()
/// Use `parse` for incremental parsing. `parse` should be called
/// many times with partial chunks of the source data. Send an empty buffer
/// to signal you don't have any more chunks to send.
///
/// The following example shows how you can implement incremental parsing:
///
/// let parser = JSONParser()
///
/// while true {
/// let buffer = try stream.read(upTo: bufferSize)
/// if let json = try parser.parse(buffer) {
/// return json
/// }
/// }
///
/// - parameter buffer: `UnsafeBufferPointer` that points to the chunk
/// used to update the state of the parser.
///
/// - throws: Throws when `buffer` is an invalid input for the given parser.
///
/// - returns: Returns `nil` if the parser was not able to produce a result yet.
/// Otherwise returns the parsed value.
@discardableResult func parse(_ buffer: UnsafeBufferPointer<Byte>) throws -> Map?
@discardableResult func parse(_ buffer: BufferRepresentable) throws -> Map?
func finish() throws -> Map
static func parse(_ buffer: UnsafeBufferPointer<Byte>) throws -> Map
static func parse(_ buffer: BufferRepresentable) throws -> Map
static func parse(_ stream: InputStream, bufferSize: Int, deadline: Double) throws -> Map
}
extension MapParser {
public func finish() throws -> Map {
guard let map = try self.parse(UnsafeBufferPointer()) else {
throw MapParserError.invalidInput
}
return map
}
public func parse(_ buffer: BufferRepresentable) throws -> Map? {
return try buffer.buffer.withUnsafeBufferPointer({ try parse($0) })
}
public static func parse(_ buffer: UnsafeBufferPointer<Byte>) throws -> Map {
let parser = self.init()
if let map = try parser.parse(buffer) {
return map
}
return try parser.finish()
}
public static func parse(_ buffer: BufferRepresentable) throws -> Map {
return try buffer.buffer.withUnsafeBufferPointer({ try parse($0) })
}
public static func parse(_ stream: InputStream, bufferSize: Int = 4096, deadline: Double) throws -> Map {
let parser = self.init()
let buffer = UnsafeMutableBufferPointer<Byte>(capacity: bufferSize)
defer { buffer.deallocate(capacity: bufferSize) }
while true {
let readBuffer = try stream.read(into: buffer, deadline: deadline)
if let result = try parser.parse(readBuffer) {
return result
}
}
}
}
public enum MapSerializerError : Error {
case invalidInput
}
public protocol MapSerializer {
init()
func serialize(_ map: Map, bufferSize: Int, body: (UnsafeBufferPointer<Byte>) throws -> Void) throws
static func serialize(_ map: Map, bufferSize: Int) throws -> Buffer
static func serialize(_ map: Map, stream: OutputStream, bufferSize: Int, deadline: Double) throws
}
extension MapSerializer {
public static func serialize(_ map: Map, bufferSize: Int = 4096) throws -> Buffer {
let serializer = self.init()
var buffer = Buffer()
try serializer.serialize(map, bufferSize: bufferSize) { writeBuffer in
buffer.append(writeBuffer)
}
guard !buffer.isEmpty else {
throw MapSerializerError.invalidInput
}
return buffer
}
public static func serialize(_ map: Map, stream: OutputStream, bufferSize: Int = 4096, deadline: Double) throws {
let serializer = self.init()
try serializer.serialize(map, bufferSize: bufferSize) { buffer in
try stream.write(buffer, deadline: deadline)
}
try stream.flush(deadline: deadline)
}
}
// MARK: Initializers
extension Map {
public init<T: MapRepresentable>(_ value: T?) {
self = value?.map ?? .null
}
public init<T: MapRepresentable>(_ values: [T]?) {
if let values = values {
self = .array(values.map({$0.map}))
} else {
self = .null
}
}
public init<T: MapRepresentable>(_ values: [T?]?) {
if let values = values {
self = .array(values.map({$0?.map ?? .null}))
} else {
self = .null
}
}
public init<T: MapRepresentable>(_ values: [String: T]?) {
if let values = values {
var dictionary: [String: Map] = [:]
for (key, value) in values.map({($0.key, $0.value.map)}) {
dictionary[key] = value
}
self = .dictionary(dictionary)
} else {
self = .null
}
}
public init<T: MapRepresentable>(_ values: [String: T?]?) {
if let values = values {
var dictionary: [String: Map] = [:]
for (key, value) in values.map({($0.key, $0.value?.map ?? .null)}) {
dictionary[key] = value
}
self = .dictionary(dictionary)
} else {
self = .null
}
}
}
// MARK: is<Type>
extension Map {
public var isNull: Bool {
if case .null = self {
return true
}
return false
}
public var isBool: Bool {
if case .bool = self {
return true
}
return false
}
public var isDouble: Bool {
if case .double = self {
return true
}
return false
}
public var isInt: Bool {
if case .int = self {
return true
}
return false
}
public var isString: Bool {
if case .string = self {
return true
}
return false
}
public var isBuffer: Bool {
if case .buffer = self {
return true
}
return false
}
public var isArray: Bool {
if case .array = self {
return true
}
return false
}
public var isDictionary: Bool {
if case .dictionary = self {
return true
}
return false
}
}
// MARK: as<type>?
extension Map {
public var bool: Bool? {
return try? get()
}
public var double: Double? {
return try? get()
}
public var int: Int? {
return try? get()
}
public var string: String? {
return try? get()
}
public var buffer: Buffer? {
return try? get()
}
public var array: [Map]? {
return try? get()
}
public var dictionary: [String: Map]? {
return try? get()
}
}
// MARK: try as<type>()
extension Map {
public func asBool(converting: Bool = false) throws -> Bool {
guard converting else {
return try get()
}
switch self {
case .bool(let value):
return value
case .int(let value):
return value != 0
case .double(let value):
return value != 0
case .string(let value):
switch value.lowercased() {
case "true": return true
case "false": return false
default: throw MapError.incompatibleType
}
case .buffer(let value):
return !value.isEmpty
case .array(let value):
return !value.isEmpty
case .dictionary(let value):
return !value.isEmpty
case .null:
return false
}
}
public func asInt(converting: Bool = false) throws -> Int {
guard converting else {
return try get()
}
switch self {
case .bool(let value):
return value ? 1 : 0
case .int(let value):
return value
case .double(let value):
return Int(value)
case .string(let value):
if let int = Int(value) {
return int
}
throw MapError.incompatibleType
case .null:
return 0
default:
throw MapError.incompatibleType
}
}
public func asDouble(converting: Bool = false) throws -> Double {
guard converting else {
return try get()
}
switch self {
case .bool(let value):
return value ? 1.0 : 0.0
case .int(let value):
return Double(value)
case .double(let value):
return value
case .string(let value):
if let double = Double(value) {
return double
}
throw MapError.incompatibleType
case .null:
return 0
default:
throw MapError.incompatibleType
}
}
public func asString(converting: Bool = false) throws -> String {
guard converting else {
return try get()
}
switch self {
case .bool(let value):
return String(value)
case .int(let value):
return String(value)
case .double(let value):
return String(value)
case .string(let value):
return value
case .buffer(let value):
return try String(buffer: value)
case .array:
throw MapError.incompatibleType
case .dictionary:
throw MapError.incompatibleType
case .null:
return "null"
}
}
public func asBuffer(converting: Bool = false) throws -> Buffer {
guard converting else {
return try get()
}
switch self {
case .bool(let value):
return value ? Buffer([0xff]) : Buffer([0x00])
case .string(let value):
return Buffer(value)
case .buffer(let value):
return value
case .null:
return Buffer()
default:
throw MapError.incompatibleType
}
}
public func asArray(converting: Bool = false) throws -> [Map] {
guard converting else {
return try get()
}
switch self {
case .array(let value):
return value
case .null:
return []
default:
throw MapError.incompatibleType
}
}
public func asDictionary(converting: Bool = false) throws -> [String: Map] {
guard converting else {
return try get()
}
switch self {
case .dictionary(let value):
return value
case .null:
return [:]
default:
throw MapError.incompatibleType
}
}
}
// MARK: IndexPath
extension String {
public func indexPath() -> [IndexPathValue] {
return self.split(separator: ".").map {
if let index = Int($0) {
return .index(index)
}
return .key($0)
}
}
}
extension IndexPathElement {
var constructEmptyContainer: Map {
switch indexPathValue {
case .index: return []
case .key: return [:]
}
}
}
// MARK: Get
extension Map {
public func get<T : MapInitializable>(_ indexPath: IndexPathElement...) throws -> T {
let map = try get(indexPath)
return try T(map: map)
}
public func get<T>(_ indexPath: IndexPathElement...) throws -> T {
if indexPath.isEmpty {
switch self {
case .bool(let value as T): return value
case .int(let value as T): return value
case .double(let value as T): return value
case .string(let value as T): return value
case .buffer(let value as T): return value
case .array(let value as T): return value
case .dictionary(let value as T): return value
default: throw MapError.incompatibleType
}
}
return try get(indexPath).get()
}
public func get(_ indexPath: IndexPathElement...) throws -> Map {
return try get(indexPath)
}
public func get(_ indexPath: [IndexPathElement]) throws -> Map {
var value: Map = self
for element in indexPath {
switch element.indexPathValue {
case .index(let index):
let array: [Map] = try value.asArray()
if array.indices.contains(index) {
value = array[index]
} else {
throw MapError.outOfBounds
}
case .key(let key):
let dictionary = try value.asDictionary()
if let newValue = dictionary[key] {
value = newValue
} else {
throw MapError.valueNotFound
}
}
}
return value
}
}
// MARK: Set
extension Map {
public mutating func set<T : MapRepresentable>(_ value: T, for indexPath: IndexPathElement...) throws {
try set(value, for: indexPath)
}
public mutating func set<T : MapRepresentable>(_ value: T, for indexPath: [IndexPathElement]) throws {
try set(value, for: indexPath, merging: true)
}
fileprivate mutating func set<T : MapRepresentable>(_ value: T, for indexPath: [IndexPathElement], merging: Bool) throws {
var indexPath = indexPath
guard let first = indexPath.first else {
return self = value.map
}
indexPath.removeFirst()
if indexPath.isEmpty {
switch first.indexPathValue {
case .index(let index):
if case .array(var array) = self {
if !array.indices.contains(index) {
throw MapError.outOfBounds
}
array[index] = value.map
self = .array(array)
} else {
throw MapError.incompatibleType
}
case .key(let key):
if case .dictionary(var dictionary) = self {
let newValue = value.map
if let existingDictionary = dictionary[key]?.dictionary,
let newDictionary = newValue.dictionary,
merging {
var combinedDictionary: [String: Map] = [:]
for (key, value) in existingDictionary {
combinedDictionary[key] = value
}
for (key, value) in newDictionary {
combinedDictionary[key] = value
}
dictionary[key] = .dictionary(combinedDictionary)
} else {
dictionary[key] = newValue
}
self = .dictionary(dictionary)
} else {
throw MapError.incompatibleType
}
}
} else {
var next = (try? self.get(first)) ?? first.constructEmptyContainer
try next.set(value, for: indexPath)
try self.set(next, for: [first])
}
}
}
// MARK: Remove
extension Map {
public mutating func remove(_ indexPath: IndexPathElement...) throws {
try self.remove(indexPath)
}
public mutating func remove(_ indexPath: [IndexPathElement]) throws {
var indexPath = indexPath
guard let first = indexPath.first else {
return self = .null
}
indexPath.removeFirst()
if indexPath.isEmpty {
guard case .dictionary(var dictionary) = self, case .key(let key) = first.indexPathValue else {
throw MapError.incompatibleType
}
dictionary[key] = nil
self = .dictionary(dictionary)
} else {
guard var next = try? self.get(first) else {
throw MapError.valueNotFound
}
try next.remove(indexPath)
try self.set(next, for: [first], merging: false)
}
}
}
// MARK: Subscripts
extension Map {
public subscript(indexPath: IndexPathElement...) -> Map {
get {
return self[indexPath]
}
set(value) {
self[indexPath] = value
}
}
public subscript(indexPath: [IndexPathElement]) -> Map {
get {
return (try? self.get(indexPath)) ?? nil
}
set(value) {
do {
try self.set(value, for: indexPath)
} catch {
fatalError(String(describing: error))
}
}
}
}
// MARK: Equatable
extension Map : Equatable {}
public func == (lhs: Map, rhs: Map) -> Bool {
switch (lhs, rhs) {
case (.null, .null): return true
case let (.int(l), .int(r)) where l == r: return true
case let (.bool(l), .bool(r)) where l == r: return true
case let (.string(l), .string(r)) where l == r: return true
case let (.buffer(l), .buffer(r)) where l == r: return true
case let (.double(l), .double(r)) where l == r: return true
case let (.array(l), .array(r)) where l == r: return true
case let (.dictionary(l), .dictionary(r)) where l == r: return true
default: return false
}
}
// MARK: Literal Convertibles
extension Map : ExpressibleByNilLiteral {
public init(nilLiteral value: Void) {
self = .null
}
}
extension Map : ExpressibleByBooleanLiteral {
public init(booleanLiteral value: BooleanLiteralType) {
self = .bool(value)
}
}
extension Map : ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self = .int(value)
}
}
extension Map : ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self = .double(value)
}
}
extension Map : ExpressibleByStringLiteral {
public init(unicodeScalarLiteral value: String) {
self = .string(value)
}
public init(extendedGraphemeClusterLiteral value: String) {
self = .string(value)
}
public init(stringLiteral value: StringLiteralType) {
self = .string(value)
}
}
extension Map : ExpressibleByArrayLiteral {
public init(arrayLiteral elements: Map...) {
self = .array(elements)
}
}
extension Map : ExpressibleByDictionaryLiteral {
public init(dictionaryLiteral elements: (String, Map)...) {
var dictionary = [String: Map](minimumCapacity: elements.count)
for (key, value) in elements {
dictionary[key] = value
}
self = .dictionary(dictionary)
}
}
// MARK: CustomStringConvertible
extension Map : CustomStringConvertible {
public var description: String {
let escapeMapping: [UnicodeScalar: String.UnicodeScalarView] = [
"\r": "\\r",
"\n": "\\n",
"\t": "\\t",
"\\": "\\\\",
"\"": "\\\"",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
]
func escape(_ source: String) -> String {
var string: String.UnicodeScalarView = "\""
for scalar in source.unicodeScalars {
if let escaped = escapeMapping[scalar] {
string.append(contentsOf: escaped)
} else {
string.append(scalar)
}
}
string.append("\"")
return String(string)
}
func serialize(map: Map) -> String {
switch map {
case .null: return "null"
case .bool(let bool): return String(bool)
case .double(let number): return String(number)
case .int(let number): return String(number)
case .string(let string): return escape(string)
case .buffer(let buffer): return "0x" + buffer.hexadecimalString()
case .array(let array): return serialize(array: array)
case .dictionary(let dictionary): return serialize(dictionary: dictionary)
}
}
func serialize(array: [Map]) -> String {
var string = "["
for index in 0 ..< array.count {
string += serialize(map: array[index])
if index != array.count - 1 {
string += ","
}
}
return string + "]"
}
func serialize(dictionary: [String: Map]) -> String {
var string = "{"
var index = 0
for (key, value) in dictionary.sorted(by: {$0.0 < $1.0}) {
string += escape(key) + ":" + serialize(map: value)
if index != dictionary.count - 1 {
string += ","
}
index += 1
}
return string + "}"
}
return serialize(map: self)
}
}
| ffec7b4440ebfb2f3e6497a364df4380 | 25.005896 | 126 | 0.536934 | false | false | false | false |
devpunk/cartesian | refs/heads/master | cartesian/View/Store/VStoreCellPurchased.swift | mit | 1 | import UIKit
class VStoreCellPurchased:VStoreCell
{
override init(frame:CGRect)
{
super.init(frame:frame)
backgroundColor = UIColor.cartesianBlue
isUserInteractionEnabled = false
let label:UILabel = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.isUserInteractionEnabled = false
label.textAlignment = NSTextAlignment.center
label.font = UIFont.medium(size:16)
label.textColor = UIColor.white
label.text = NSLocalizedString("VStoreCellPurchased_label", comment:"")
addSubview(label)
NSLayoutConstraint.equals(
view:label,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
}
| 6383879e0ed7d6131badab25eef11547 | 25.433333 | 79 | 0.627995 | false | false | false | false |
nkirby/Humber | refs/heads/master | _lib/HMGithub/_src/Sync/SyncController+Notifications.swift | mit | 1 | // =======================================================
// HMGithub
// Nathaniel Kirby
// =======================================================
import Foundation
import ReactiveCocoa
import Result
import HMCore
// =======================================================
public protocol GithubNotificationsSyncProviding {
func syncAccountNotifications() -> SignalProducer<Void, SyncError>
}
extension SyncController: GithubNotificationsSyncProviding {
public func syncAccountNotifications() -> SignalProducer<Void, SyncError> {
guard let api = ServiceController.component(GithubAPINotificationProviding.self),
let data = ServiceController.component(GithubNotificationDataProviding.self) else {
return SignalProducer.empty
}
return api.getNotifications()
.observeOn(CoreScheduler.background())
.mapError { _ in return SyncError.Unknown }
.flatMap(.Latest, transform: { responses -> SignalProducer<Void, SyncError> in
return SignalProducer { observer, _ in
data.saveAccountNotifications(notificationResponses: responses, write: true)
observer.sendNext()
observer.sendCompleted()
}
})
}
}
| 5706c6dd5fc0b82bd806f4c41bd6d3a2 | 34.918919 | 96 | 0.563582 | false | false | false | false |
slavapestov/swift | refs/heads/master | test/decl/func/functions.swift | apache-2.0 | 1 | // RUN: %target-parse-verify-swift
infix operator ==== {}
infix operator <<<< {}
infix operator <><> {}
// <rdar://problem/13782566>
// Check that func op<T>() parses without a space between the name and the
// generic parameter list.
func ====<T>(x: T, y: T) {}
func <<<<<T>(x: T, y: T) {}
func <><><T>(x: T, y: T) {}
//===--- Check that we recover when the parameter tuple is missing.
func recover_missing_parameter_tuple_1 { // expected-error {{expected '(' in argument list of function declaration}}
}
func recover_missing_parameter_tuple_1a // expected-error {{expected '(' in argument list of function declaration}}
{
}
func recover_missing_parameter_tuple_2<T> { // expected-error {{expected '(' in argument list of function declaration}} expected-error {{generic parameter 'T' is not used in function signature}}
}
func recover_missing_parameter_tuple_3 -> Int { // expected-error {{expected '(' in argument list of function declaration}}
}
func recover_missing_parameter_tuple_4<T> -> Int { // expected-error {{expected '(' in argument list of function declaration}} expected-error {{generic parameter 'T' is not used in function signature}}
}
//===--- Check that we recover when the function return type is missing.
// Note: Don't move braces to a different line here.
func recover_missing_return_type_1() -> // expected-error {{expected type for function result}}
{
}
func recover_missing_return_type_2() -> // expected-error {{expected type for function result}} expected-error{{expected '{' in body of function declaration}}
// Note: Don't move braces to a different line here.
func recover_missing_return_type_3 -> // expected-error {{expected '(' in argument list of function declaration}} expected-error {{expected type for function result}}
{
}
//===--- Check that we recover if ':' was used instead of '->' to specify the return type.
func recover_colon_arrow_1() : Int { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=->}}
func recover_colon_arrow_2() : { } // expected-error {{expected '->' after function parameter tuple}} {{30-31=->}} expected-error {{expected type for function result}}
func recover_colon_arrow_3 : Int { } // expected-error {{expected '->' after function parameter tuple}} {{28-29=->}} expected-error {{expected '(' in argument list of function declaration}}
func recover_colon_arrow_4 : { } // expected-error {{expected '->' after function parameter tuple}} {{28-29=->}} expected-error {{expected '(' in argument list of function declaration}} expected-error {{expected type for function result}}
//===--- Check that we recover if the function does not have a body, but the
//===--- context requires the function to have a body.
func recover_missing_body_1() // expected-error {{expected '{' in body of function declaration}}
func recover_missing_body_2() // expected-error {{expected '{' in body of function declaration}}
-> Int
// Ensure that we don't skip over the 'func g' over to the right paren in
// function g, while recovering from parse error in f() parameter tuple. We
// should produce the error about missing right paren.
//
// FIXME: The errors are awful. We should produce just the error about paren.
func f_recover_missing_tuple_paren(a: Int // expected-note {{to match this opening '('}} expected-error{{expected '{' in body of function declaration}} expected-error {{expected ')' in parameter}}
func g_recover_missing_tuple_paren(b: Int) {
}
//===--- Parse errors.
func parseError1a(a: ) {} // expected-error {{expected parameter type following ':'}}
func parseError1b(a: // expected-error {{expected parameter type following ':'}}
) {}
func parseError2(a: Int, b: ) {} // expected-error {{expected parameter type following ':'}}
func parseError3(a: unknown_type, b: ) {} // expected-error {{use of undeclared type 'unknown_type'}} expected-error {{expected parameter type following ':'}}
func parseError4(a: , b: ) {} // expected-error 2{{expected parameter type following ':'}}
func parseError5(a: b: ) {} // expected-error {{use of undeclared type 'b'}} expected-error 2 {{expected ',' separator}} {{22-22=,}} {{22-22=,}} expected-error {{expected parameter name followed by ':'}}
func parseError6(a: unknown_type, b: ) {} // expected-error {{use of undeclared type 'unknown_type'}} expected-error {{expected parameter type following ':'}}
func parseError7(a: Int, goo b: unknown_type) {} // expected-error {{use of undeclared type 'unknown_type'}}
public func foo(a: Bool = true) -> (b: Bar, c: Bar) {} // expected-error {{use of undeclared type 'Bar'}}
func parenPatternInArg((a): Int) -> Int { // expected-error {{expected parameter name followed by ':'}} expected-error {{expected ',' separator}}
return a // expected-error {{use of unresolved identifier 'a'}}
}
parenPatternInArg(0) // expected-error {{argument passed to call that takes no arguments}}
var nullaryClosure: Int -> Int = {_ in 0}
nullaryClosure(0)
// rdar://16737322 - This argument is an unnamed argument that has a labeled
// tuple type as the type. Because the labels are in the type, they are not
// parameter labels, and they are thus not in scope in the body of the function.
// expected-error@+1{{unnamed parameters must be written}} {{27-27=_: }}
func destructureArgument( (result: Int, error: Bool) ) -> Int {
return result // expected-error {{use of unresolved identifier 'result'}}
}
// The former is the same as this:
func destructureArgument2(a: (result: Int, error: Bool) ) -> Int {
return result // expected-error {{use of unresolved identifier 'result'}}
}
class ClassWithObjCMethod {
@objc
func someMethod(x : Int) {}
}
func testObjCMethodCurry(a : ClassWithObjCMethod) -> (Int) -> () {
return a.someMethod
}
// We used to crash on this.
func rdar16786220(inout let c: Int) -> () { // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{25-29=}}
c = 42
}
// <rdar://problem/17763388> ambiguous operator emits same candidate multiple times
infix operator !!! {}
func !!!<T>(lhs: Array<T>, rhs: Array<T>) -> Bool { return false }
func !!!<T>(lhs: UnsafePointer<T>, rhs: UnsafePointer<T>) -> Bool { return false }
[1] !!! [1] // unambiguously picking the array overload.
// <rdar://problem/16786168> Functions currently permit 'var inout' parameters
func var_inout_error(inout var x : Int) {} // expected-error {{parameter may not have multiple 'inout', 'var', or 'let' specifiers}} {{28-32=}}
// Unnamed parameters require the name "_":
func unnamed(Int) { } // expected-error{{unnamed parameters must be written with the empty name '_'}}{{14-14=_: }}
// Test fixits on curried functions.
func testCurryFixits() {
func f1(x: Int)(y: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{17-19=, }}
func f1a(x: Int, y: Int) {}
func f2(x: Int)(y: Int)(z: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{17-19=, }} {{25-27=, }}
func f2a(x: Int, y: Int, z: Int) {}
func f3(x: Int)() {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{17-19=}}
func f3a(x: Int) {}
func f4()(x: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{11-13=}}
func f4a(x: Int) {}
func f5(x: Int)()(y: Int) {} // expected-error{{curried function declaration syntax has been removed; use a single parameter list}} {{17-19=}} {{19-21=, }}
func f5a(x: Int, y: Int) {}
}
| a7335c562f5e7f1cac9437719acd9090 | 48.487013 | 244 | 0.684556 | false | false | false | false |
DanielZakharin/Shelfie | refs/heads/master | Shelfie/Pods/PieCharts/PieCharts/Layer/Impl/PlainText/PiePlainTextLayer.swift | gpl-3.0 | 1 | //
// PiePlainTextLayer.swift
// PieCharts
//
// Created by Ivan Schuetz on 30/12/2016.
// Copyright © 2016 Ivan Schuetz. All rights reserved.
//
import UIKit
open class PiePlainTextLayerSettings: PieCustomViewsLayerSettings {
public var label: PieChartLabelSettings = PieChartLabelSettings()
}
open class PiePlainTextLayer: PieChartLayer {
public weak var chart: PieChart?
public var settings: PiePlainTextLayerSettings = PiePlainTextLayerSettings()
public var onNotEnoughSpace: ((UILabel, CGSize) -> Void)?
fileprivate var sliceViews = [PieSlice: UILabel]()
public var animator: PieViewLayerAnimator = AlphaPieViewLayerAnimator()
public init() {}
public func onEndAnimation(slice: PieSlice) {
addItems(slice: slice)
}
public func addItems(slice: PieSlice) {
guard sliceViews[slice] == nil else {return}
let label: UILabel = settings.label.labelGenerator?(slice) ?? {
let label = UILabel()
label.backgroundColor = settings.label.bgColor
label.textColor = settings.label.textColor
label.font = settings.label.font
return label
}()
let text = settings.label.textGenerator(slice)
let size = (text as NSString).size(withAttributes: [NSAttributedStringKey.font: settings.label.font])
let center = settings.viewRadius.map{slice.view.midPoint(radius: $0)} ?? slice.view.arcCenter
let availableSize = CGSize(width: slice.view.maxRectWidth(center: center, height: size.height), height: size.height)
if !settings.hideOnOverflow || availableSize.contains(size) {
label.text = text
label.sizeToFit()
} else {
onNotEnoughSpace?(label, availableSize)
}
label.center = center
chart?.addSubview(label)
animator.animate(label)
sliceViews[slice] = label
}
public func onSelected(slice: PieSlice, selected: Bool) {
guard let label = sliceViews[slice] else {print("Invalid state: slice not in dictionary"); return}
let p = slice.view.calculatePosition(angle: slice.view.midAngle, p: label.center, offset: selected ? slice.view.selectedOffset : -slice.view.selectedOffset)
UIView.animate(withDuration: 0.15) {
label.center = p
}
}
public func clear() {
for (_, view) in sliceViews {
view.removeFromSuperview()
}
sliceViews.removeAll()
}
}
| e81e5f476d58293dd862f35303097059 | 30.97561 | 164 | 0.626621 | false | false | false | false |
bradya/tracker | refs/heads/master | tracker/DetailViewController.swift | mit | 1 | //
// DetailViewController.swift
// tracker
//
// Created by Brady Archambo on 9/2/14.
// Copyright (c) 2014 Boa. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var noteTextView: UITextView!
let placeholder: String = "Type here..."
var detailItem: AnyObject? {
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
self.automaticallyAdjustsScrollViewInsets = false
// Update the user interface for the detail item.
if let detail: AnyObject = self.detailItem {
if let textView = self.noteTextView {
let note: AnyObject! = detail.valueForKey("note")
textView.text = note != nil ? note.description : ""
textView.contentInset = UIEdgeInsetsMake(8, 0, 8, 0)
textView.scrollIndicatorInsets = UIEdgeInsetsMake(8, 0, 8, 0)
textView.delegate = self
}
}
}
override func viewWillAppear(animated: Bool) {
self.noteTextView.becomeFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.configureView()
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil)
}
func textViewDidChange(textView: UITextView) {
if let detail: AnyObject = self.detailItem {
detail.setValue(self.noteTextView.text, forKey: "note")
}
}
func keyboardWillShow(note: NSNotification) {
if let userInfo: NSDictionary = note.userInfo {
if let frame: CGRect = userInfo.valueForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue() {
var contentInsets: UIEdgeInsets = self.noteTextView.contentInset
contentInsets.bottom = CGRectGetHeight(frame)
self.noteTextView.contentInset = contentInsets
self.noteTextView.scrollIndicatorInsets = contentInsets
}
}
}
func keyboardWillHide(note: NSNotification) {
var contentInsets = self.noteTextView.contentInset
contentInsets.bottom = 0.0;
self.noteTextView.contentInset = contentInsets;
self.noteTextView.scrollIndicatorInsets = contentInsets;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| ea44786cf5881e472713fd2ba4fdb284 | 32.697674 | 154 | 0.624914 | false | false | false | false |
oskarpearson/rileylink_ios | refs/heads/master | MinimedKit/Messages/GetPumpModelCarelinkMessageBody.swift | mit | 1 | //
// GetPumpModelCarelinkMessageBody.swift
// RileyLink
//
// Created by Pete Schwamb on 3/12/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public class GetPumpModelCarelinkMessageBody: CarelinkLongMessageBody {
public let model: String
public required init?(rxData: Data) {
guard rxData.count == type(of: self).length,
let mdl = String(data: rxData.subdata(in: 2..<5), encoding: String.Encoding.ascii) else {
model = ""
super.init(rxData: rxData)
return nil
}
model = mdl
super.init(rxData: rxData)
}
public required init?(rxData: NSData) {
fatalError("init(rxData:) has not been implemented")
}
}
| 9500821bd42d87daf7e677587ee464af | 26.357143 | 101 | 0.617493 | false | false | false | false |
CoderST/DYZB | refs/heads/master | DYZB/DYZB/Class/Main/View/STCollectionView.swift | mit | 1 | //
// STCollectionView.swift
// DYZB
//
// Created by xiudou on 2017/7/13.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
fileprivate let STCollectionViewCellIdentifier = "STCollectionViewCellIdentifier"
fileprivate let STLocationReusableViewIdentifier = "STLocationReusableViewIdentifier"
@objc protocol STCollectionViewDataSource : class {
/*********必须实现***********/
// func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
/// 多少行
@objc func collectionView(_ stCollectionView: STCollectionView, numberOfItemsInSection section: Int) -> Int
/// 每行的标题
@objc func collectionViewTitleInRow(_ stCollectionView : STCollectionView, _ indexPath : IndexPath)->String
/*********选择实现***********/
/// 普通图片
// @objc optional func imageName(_ collectionView : STCollectionView, _ indexPath : IndexPath)->String
/// 高亮图片
// @objc optional func highImageName(_ collectionView : STCollectionView, _ indexPath : IndexPath)->String
/// 多少区间
@objc optional func numberOfSections(in stCollectionView: STCollectionView) -> Int
/// 是否有箭头
@objc optional func isHiddenArrowImageView(_ stCollectionView : STCollectionView, _ indexPath : IndexPath)->Bool
}
@objc protocol STCollectionViewDelegate : class{
/// 点击事件
@objc optional func stCollection(_ stCollectionView : STCollectionView, didSelectItemAt indexPath: IndexPath)
// 区间头部head的文字
@objc optional func stCollectionHeadInSection(_ stCollectionView: STCollectionView, at indexPath: IndexPath) -> String
}
class STCollectionView: UIView {
weak var dataSource : STCollectionViewDataSource?
weak var delegate : STCollectionViewDelegate?
// MARK:- 懒加载
lazy var collectionView : UICollectionView = {
// 设置layout属性
let layout = XDPlanFlowLayout()
layout.naviHeight = 64
let width = sScreenW
// 默认值(如果改动可以添加代理方法)
layout.itemSize = CGSize(width: width, height: 44)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.headerReferenceSize = CGSize(width: sScreenW, height: 20)
// 创建UICollectionView
let collectionView = UICollectionView(frame: CGRect(x: 0, y:0 , width: 0 , height: 0), collectionViewLayout: layout)
collectionView.showsVerticalScrollIndicator = false
collectionView.showsHorizontalScrollIndicator = false
collectionView.backgroundColor = UIColor(r: 239, g: 239, b: 239)
// 注册cell
collectionView.register(STCollectionViewCell.self, forCellWithReuseIdentifier: STCollectionViewCellIdentifier)
collectionView.register(LocationReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: STLocationReusableViewIdentifier)
return collectionView;
}()
override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = bounds
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(collectionView)
// 设置数据源
collectionView.dataSource = self
collectionView.delegate = self
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension STCollectionView : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int{
let sectionCount = dataSource?.numberOfSections?(in: self)
if sectionCount == nil || sectionCount == 0 {
return 1
}else{
return sectionCount!
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
guard let itemsCount = dataSource?.collectionView(self, numberOfItemsInSection: section) else { return 0 }
return itemsCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: STCollectionViewCellIdentifier, for: indexPath) as! STCollectionViewCell
cell.contentView.backgroundColor = UIColor.randomColor()
// title
let text = dataSource?.collectionViewTitleInRow(self, indexPath) ?? ""
cell.titleLabel.text = text
// 是否右箭头
if let isHidden = dataSource?.isHiddenArrowImageView?(self, indexPath){
cell.arrowImageView.isHidden = isHidden
}else{
cell.arrowImageView.isHidden = true
}
// 必须添加下面这句话,不然系统不知道什么时候刷新cell(参考:http://www.jianshu.com/writer#/notebooks/8510661/notes/14529933/preview)
cell.setNeedsLayout()
return cell
}
}
extension STCollectionView : UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
delegate?.stCollection?(self, didSelectItemAt: indexPath)
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let view = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: STLocationReusableViewIdentifier, for: indexPath) as! LocationReusableView
view.titleString = delegate?.stCollectionHeadInSection?(self, at: indexPath)
return view
}
}
| 17ec28e7d585181778ebd64dfd1b782d | 34.981132 | 208 | 0.683447 | false | false | false | false |
bwide/Sorting-Algorithms-Playground | refs/heads/master | Sorting algorithms.playground/Pages/BubbleSort.xcplaygroundpage/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
import PlaygroundSupport
let arraySize = 50
let array = VisualSortableArray.init(arraySize: arraySize)
func compare(i: Int, j: Int) -> Int{
return array.compare(i: i, j: j)
}
func swap(i: Int, j: Int){
array.swap(i: i, j: j)
}
func select(i: Int, j: Int) -> Bool {
return array.select(i: i, j: j)
}
PlaygroundPage.current.liveView = array.view
DispatchQueue.global(qos: .background).async {
sleep(2)
while true {
var swapped = false
for i in 1..<array.count {
select(i: i, j: i-1)
if compare(i: i, j: i-1) < 0{
swap(i: i, j: i-1)
swapped = true
}
}
if !swapped {
break
}
}
}
| 81097bb97a6289c244e5d2f98d8fee36 | 17.282609 | 58 | 0.514863 | false | false | false | false |
Nyx0uf/MPDRemote | refs/heads/master | src/common/extensions/FileManager+Extensions.swift | mit | 1 | // FileManager+Extensions.swift
// Copyright (c) 2017 Nyx0uf
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
extension FileManager
{
func sizeOfDirectoryAtURL(_ directoryURL: URL) -> Int
{
var result = 0
let props = [URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
do
{
let ar = try self.contentsOfDirectory(at: directoryURL, includingPropertiesForKeys: props, options: [])
for url in ar
{
var isDir: ObjCBool = false
self.fileExists(atPath: url.path, isDirectory: &isDir)
if isDir.boolValue
{
result += self.sizeOfDirectoryAtURL(url)
}
else
{
result += try self.attributesOfItem(atPath: url.path)[FileAttributeKey.size] as! Int
}
}
}
catch let error
{
Logger.shared.log(type: .error, message: "Can't get directory size (\(error.localizedDescription)")
}
return result
}
}
| 0fb2cc3c953a0c2bb500812d5b00acc1 | 33.438596 | 123 | 0.737646 | false | false | false | false |
fei1990/PageScaledScroll | refs/heads/master | ScaledPageView/Pods/EZSwiftExtensions/Sources/UIViewExtensions.swift | mit | 1 | //
// UIViewExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import UIKit
// MARK: Custom UIView Initilizers
extension UIView {
/// EZSwiftExtensions
public convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
self.init(frame: CGRect(x: x, y: y, width: w, height: h))
}
/// EZSwiftExtensions, puts padding around the view
public convenience init(superView: UIView, padding: CGFloat) {
self.init(frame: CGRect(x: superView.x + padding, y: superView.y + padding, width: superView.w - padding*2, height: superView.h - padding*2))
}
/// EZSwiftExtensions - Copies size of superview
public convenience init(superView: UIView) {
self.init(frame: CGRect(origin: CGPoint.zero, size: superView.size))
}
}
// MARK: Frame Extensions
extension UIView {
//TODO: Multipe addsubview
//TODO: Add pics to readme
/// EZSwiftExtensions, resizes this view so it fits the largest subview
public func resizeToFitSubviews() {
var width: CGFloat = 0
var height: CGFloat = 0
for someView in self.subviews {
let aView = someView
let newWidth = aView.x + aView.w
let newHeight = aView.y + aView.h
width = max(width, newWidth)
height = max(height, newHeight)
}
frame = CGRect(x: x, y: y, width: width, height: height)
}
/// EZSwiftExtensions, resizes this view so it fits the largest subview
public func resizeToFitSubviews(tagsToIgnore: [Int]) {
var width: CGFloat = 0
var height: CGFloat = 0
for someView in self.subviews {
let aView = someView
if !tagsToIgnore.contains(someView.tag) {
let newWidth = aView.x + aView.w
let newHeight = aView.y + aView.h
width = max(width, newWidth)
height = max(height, newHeight)
}
}
frame = CGRect(x: x, y: y, width: width, height: height)
}
/// EZSwiftExtensions
public func resizeToFitWidth() {
let currentHeight = self.h
self.sizeToFit()
self.h = currentHeight
}
/// EZSwiftExtensions
public func resizeToFitHeight() {
let currentWidth = self.w
self.sizeToFit()
self.w = currentWidth
}
/// EZSwiftExtensions
public var x: CGFloat {
get {
return self.frame.origin.x
} set(value) {
self.frame = CGRect(x: value, y: self.y, width: self.w, height: self.h)
}
}
/// EZSwiftExtensions
public var y: CGFloat {
get {
return self.frame.origin.y
} set(value) {
self.frame = CGRect(x: self.x, y: value, width: self.w, height: self.h)
}
}
/// EZSwiftExtensions
public var w: CGFloat {
get {
return self.frame.size.width
} set(value) {
self.frame = CGRect(x: self.x, y: self.y, width: value, height: self.h)
}
}
/// EZSwiftExtensions
public var h: CGFloat {
get {
return self.frame.size.height
} set(value) {
self.frame = CGRect(x: self.x, y: self.y, width: self.w, height: value)
}
}
/// EZSwiftExtensions
public var left: CGFloat {
get {
return self.x
} set(value) {
self.x = value
}
}
/// EZSwiftExtensions
public var right: CGFloat {
get {
return self.x + self.w
} set(value) {
self.x = value - self.w
}
}
/// EZSwiftExtensions
public var top: CGFloat {
get {
return self.y
} set(value) {
self.y = value
}
}
/// EZSwiftExtensions
public var bottom: CGFloat {
get {
return self.y + self.h
} set(value) {
self.y = value - self.h
}
}
/// EZSwiftExtensions
public var origin: CGPoint {
get {
return self.frame.origin
} set(value) {
self.frame = CGRect(origin: value, size: self.frame.size)
}
}
/// EZSwiftExtensions
public var centerX: CGFloat {
get {
return self.center.x
} set(value) {
self.center.x = value
}
}
/// EZSwiftExtensions
public var centerY: CGFloat {
get {
return self.center.y
} set(value) {
self.center.y = value
}
}
/// EZSwiftExtensions
public var size: CGSize {
get {
return self.frame.size
} set(value) {
self.frame = CGRect(origin: self.frame.origin, size: value)
}
}
/// EZSwiftExtensions
public func leftOffset(offset: CGFloat) -> CGFloat {
return self.left - offset
}
/// EZSwiftExtensions
public func rightOffset(offset: CGFloat) -> CGFloat {
return self.right + offset
}
/// EZSwiftExtensions
public func topOffset(offset: CGFloat) -> CGFloat {
return self.top - offset
}
/// EZSwiftExtensions
public func bottomOffset(offset: CGFloat) -> CGFloat {
return self.bottom + offset
}
//TODO: Add to readme
/// EZSwiftExtensions
public func alignRight(offset: CGFloat) -> CGFloat {
return self.w - offset
}
/// EZSwiftExtensions
public func reorderSubViews(reorder: Bool = false, tagsToIgnore: [Int] = []) -> CGFloat {
var currentHeight: CGFloat = 0
for someView in subviews {
if !tagsToIgnore.contains(someView.tag) && !(someView ).hidden {
if reorder {
let aView = someView
aView.frame = CGRect(x: aView.frame.origin.x, y: currentHeight, width: aView.frame.width, height: aView.frame.height)
}
currentHeight += someView.frame.height
}
}
return currentHeight
}
public func removeSubviews() {
for subview in subviews {
subview.removeFromSuperview()
}
}
/// EZSE: Centers view in superview horizontally
public func centerXInSuperView() {
guard let parentView = superview else {
assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview")
return
}
self.x = parentView.w/2 - self.w/2
}
/// EZSE: Centers view in superview vertically
public func centerYInSuperView() {
guard let parentView = superview else {
assertionFailure("EZSwiftExtensions Error: The view \(self) doesn't have a superview")
return
}
self.y = parentView.h/2 - self.h/2
}
/// EZSE: Centers view in superview horizontally & vertically
public func centerInSuperView() {
self.centerXInSuperView()
self.centerYInSuperView()
}
}
// MARK: Transform Extensions
extension UIView {
/// EZSwiftExtensions
public func setRotationX(x: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setRotationY(y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setRotationZ(z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setRotation(x x: CGFloat, y: CGFloat, z: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DRotate(transform, x.degreesToRadians(), 1.0, 0.0, 0.0)
transform = CATransform3DRotate(transform, y.degreesToRadians(), 0.0, 1.0, 0.0)
transform = CATransform3DRotate(transform, z.degreesToRadians(), 0.0, 0.0, 1.0)
self.layer.transform = transform
}
/// EZSwiftExtensions
public func setScale(x x: CGFloat, y: CGFloat) {
var transform = CATransform3DIdentity
transform.m34 = 1.0 / -1000.0
transform = CATransform3DScale(transform, x, y, 1)
self.layer.transform = transform
}
}
// MARK: Layer Extensions
extension UIView {
/// EZSwiftExtensions
public func setCornerRadius(radius radius: CGFloat) {
self.layer.cornerRadius = radius
self.layer.masksToBounds = true
}
//TODO: add this to readme
/// EZSwiftExtensions
public func addShadow(offset offset: CGSize, radius: CGFloat, color: UIColor, opacity: Float, cornerRadius: CGFloat? = nil) {
self.layer.shadowOffset = offset
self.layer.shadowRadius = radius
self.layer.shadowOpacity = opacity
self.layer.shadowColor = color.CGColor
if let r = cornerRadius {
self.layer.shadowPath = UIBezierPath(roundedRect: bounds, cornerRadius: r).CGPath
}
}
/// EZSwiftExtensions
public func addBorder(width width: CGFloat, color: UIColor) {
layer.borderWidth = width
layer.borderColor = color.CGColor
layer.masksToBounds = true
}
/// EZSwiftExtensions
public func addBorderTop(size size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: frame.width, height: size, color: color)
}
//TODO: add to readme
/// EZSwiftExtensions
public func addBorderTopWithPadding(size size: CGFloat, color: UIColor, padding: CGFloat) {
addBorderUtility(x: padding, y: 0, width: frame.width - padding*2, height: size, color: color)
}
/// EZSwiftExtensions
public func addBorderBottom(size size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: frame.height - size, width: frame.width, height: size, color: color)
}
/// EZSwiftExtensions
public func addBorderLeft(size size: CGFloat, color: UIColor) {
addBorderUtility(x: 0, y: 0, width: size, height: frame.height, color: color)
}
/// EZSwiftExtensions
public func addBorderRight(size size: CGFloat, color: UIColor) {
addBorderUtility(x: frame.width - size, y: 0, width: size, height: frame.height, color: color)
}
/// EZSwiftExtensions
private func addBorderUtility(x x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, color: UIColor) {
let border = CALayer()
border.backgroundColor = color.CGColor
border.frame = CGRect(x: x, y: y, width: width, height: height)
layer.addSublayer(border)
}
//TODO: add this to readme
/// EZSwiftExtensions
public func drawCircle(fillColor fillColor: UIColor, strokeColor: UIColor, strokeWidth: CGFloat) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = fillColor.CGColor
shapeLayer.strokeColor = strokeColor.CGColor
shapeLayer.lineWidth = strokeWidth
self.layer.addSublayer(shapeLayer)
}
//TODO: add this to readme
/// EZSwiftExtensions
public func drawStroke(width width: CGFloat, color: UIColor) {
let path = UIBezierPath(roundedRect: CGRect(x: 0, y: 0, width: self.w, height: self.w), cornerRadius: self.w/2)
let shapeLayer = CAShapeLayer ()
shapeLayer.path = path.CGPath
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.strokeColor = color.CGColor
shapeLayer.lineWidth = width
self.layer.addSublayer(shapeLayer)
}
}
private let UIViewAnimationDuration: NSTimeInterval = 1
private let UIViewAnimationSpringDamping: CGFloat = 0.5
private let UIViewAnimationSpringVelocity: CGFloat = 0.5
//TODO: add this to readme
// MARK: Animation Extensions
extension UIView {
/// EZSwiftExtensions
public func spring(animations animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
spring(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func spring(duration duration: NSTimeInterval, animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animateWithDuration(
UIViewAnimationDuration,
delay: 0,
usingSpringWithDamping: UIViewAnimationSpringDamping,
initialSpringVelocity: UIViewAnimationSpringVelocity,
options: UIViewAnimationOptions.AllowAnimatedContent,
animations: animations,
completion: completion
)
}
/// EZSwiftExtensions
public func animate(duration duration: NSTimeInterval, animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
UIView.animateWithDuration(duration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func animate(animations animations: (() -> Void), completion: ((Bool) -> Void)? = nil) {
animate(duration: UIViewAnimationDuration, animations: animations, completion: completion)
}
/// EZSwiftExtensions
public func pop() {
setScale(x: 1.1, y: 1.1)
spring(duration: 0.2, animations: { [unowned self] () -> Void in
self.setScale(x: 1, y: 1)
})
}
/// EZSwiftExtensions
public func popBig() {
setScale(x: 1.25, y: 1.25)
spring(duration: 0.2, animations: { [unowned self] () -> Void in
self.setScale(x: 1, y: 1)
})
}
}
//TODO: add this to readme
// MARK: Render Extensions
extension UIView {
/// EZSwiftExtensions
public func toImage () -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0)
drawViewHierarchyInRect(bounds, afterScreenUpdates: false)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
// MARK: Gesture Extensions
extension UIView {
/// http://stackoverflow.com/questions/4660371/how-to-add-a-touch-event-to-a-uiview/32182866#32182866
/// EZSwiftExtensions
public func addTapGesture(tapNumber tapNumber: Int = 1, target: AnyObject, action: Selector) {
let tap = UITapGestureRecognizer(target: target, action: action)
tap.numberOfTapsRequired = tapNumber
addGestureRecognizer(tap)
userInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addTapGesture(tapNumber tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> ())?) {
let tap = BlockTap(tapCount: tapNumber, fingerCount: 1, action: action)
addGestureRecognizer(tap)
userInteractionEnabled = true
}
/// EZSwiftExtensions
public func addSwipeGesture(direction direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, target: AnyObject, action: Selector) {
let swipe = UISwipeGestureRecognizer(target: target, action: action)
swipe.direction = direction
#if os(iOS)
swipe.numberOfTouchesRequired = numberOfTouches
#endif
addGestureRecognizer(swipe)
userInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addSwipeGesture(direction direction: UISwipeGestureRecognizerDirection, numberOfTouches: Int = 1, action: ((UISwipeGestureRecognizer) -> ())?) {
let swipe = BlockSwipe(direction: direction, fingerCount: numberOfTouches, action: action)
addGestureRecognizer(swipe)
userInteractionEnabled = true
}
/// EZSwiftExtensions
public func addPanGesture(target target: AnyObject, action: Selector) {
let pan = UIPanGestureRecognizer(target: target, action: action)
addGestureRecognizer(pan)
userInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addPanGesture(action action: ((UIPanGestureRecognizer) -> ())?) {
let pan = BlockPan(action: action)
addGestureRecognizer(pan)
userInteractionEnabled = true
}
#if os(iOS)
/// EZSwiftExtensions
public func addPinchGesture(target target: AnyObject, action: Selector) {
let pinch = UIPinchGestureRecognizer(target: target, action: action)
addGestureRecognizer(pinch)
userInteractionEnabled = true
}
#endif
#if os(iOS)
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addPinchGesture(action action: ((UIPinchGestureRecognizer) -> ())?) {
let pinch = BlockPinch(action: action)
addGestureRecognizer(pinch)
userInteractionEnabled = true
}
#endif
/// EZSwiftExtensions
public func addLongPressGesture(target target: AnyObject, action: Selector) {
let longPress = UILongPressGestureRecognizer(target: target, action: action)
addGestureRecognizer(longPress)
userInteractionEnabled = true
}
/// EZSwiftExtensions - Make sure you use "[weak self] (gesture) in" if you are using the keyword self inside the closure or there might be a memory leak
public func addLongPressGesture(action action: ((UILongPressGestureRecognizer) -> ())?) {
let longPress = BlockLongPress(action: action)
addGestureRecognizer(longPress)
userInteractionEnabled = true
}
}
//TODO: add to readme
extension UIView {
/// EZSwiftExtensions [UIRectCorner.TopLeft, UIRectCorner.TopRight]
public func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.CGPath
self.layer.mask = mask
}
/// EZSwiftExtensions
public func roundView() {
self.layer.cornerRadius = min(self.frame.size.height, self.frame.size.width) / 2
}
}
extension UIView {
///EZSE: Shakes the view for as many number of times as given in the argument.
public func shakeViewForTimes(times: Int) {
let anim = CAKeyframeAnimation(keyPath: "transform")
anim.values = [
NSValue(CATransform3D: CATransform3DMakeTranslation(-5, 0, 0 )),
NSValue(CATransform3D: CATransform3DMakeTranslation( 5, 0, 0 ))
]
anim.autoreverses = true
anim.repeatCount = Float(times)
anim.duration = 7/100
self.layer.addAnimation(anim, forKey: nil)
}
}
extension UIView {
///EZSE: Loops until it finds the top root view. //TODO: Add to readme
func rootView() -> UIView {
guard let parentView = superview else {
return self
}
return parentView.rootView()
}
}
| 63b374edc345f56b86de4689105ae6c1 | 32.77911 | 160 | 0.628428 | false | false | false | false |
devpunk/cartesian | refs/heads/master | cartesian/View/DrawProject/Menu/VDrawProjectMenuEditBar.swift | mit | 1 | import UIKit
class VDrawProjectMenuEditBar:UIView, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout
{
private let model:MDrawProjectMenuEditBar
private weak var controller:CDrawProject!
private weak var collectionView:VCollection!
private let kBorderHeight:CGFloat = 1
private let kCellWidth:CGFloat = 85
private let kDeselectTime:TimeInterval = 0.2
init(controller:CDrawProject)
{
model = MDrawProjectMenuEditBar()
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let border:VBorder = VBorder(color:UIColor(white:0, alpha:0.1))
let collectionView:VCollection = VCollection()
collectionView.alwaysBounceHorizontal = true
collectionView.delegate = self
collectionView.dataSource = self
collectionView.registerCell(cell:VDrawProjectMenuEditBarCell.self)
self.collectionView = collectionView
if let flow:VCollectionFlow = collectionView.collectionViewLayout as? VCollectionFlow
{
flow.scrollDirection = UICollectionViewScrollDirection.horizontal
}
addSubview(border)
addSubview(collectionView)
NSLayoutConstraint.topToTop(
view:border,
toView:self)
NSLayoutConstraint.height(
view:border,
constant:kBorderHeight)
NSLayoutConstraint.equalsHorizontal(
view:border,
toView:self)
NSLayoutConstraint.equals(
view:collectionView,
toView:self)
}
required init?(coder:NSCoder)
{
return nil
}
//MARK: private
private func modelAtIndex(index:IndexPath) -> MDrawProjectMenuEditBarItem
{
let item:MDrawProjectMenuEditBarItem = model.items[index.item]
return item
}
//MARK: collectionView delegate
func collectionView(_ collectionView:UICollectionView, layout collectionViewLayout:UICollectionViewLayout, sizeForItemAt indexPath:IndexPath) -> CGSize
{
let height:CGFloat = collectionView.bounds.maxY
let size:CGSize = CGSize(width:kCellWidth, height:height)
return size
}
func numberOfSections(in collectionView:UICollectionView) -> Int
{
return 1
}
func collectionView(_ collectionView:UICollectionView, numberOfItemsInSection section:Int) -> Int
{
let count:Int = model.items.count
return count
}
func collectionView(_ collectionView:UICollectionView, cellForItemAt indexPath:IndexPath) -> UICollectionViewCell
{
let item:MDrawProjectMenuEditBarItem = modelAtIndex(index:indexPath)
let cell:VDrawProjectMenuEditBarCell = collectionView.dequeueReusableCell(
withReuseIdentifier:
VDrawProjectMenuEditBarCell.reusableIdentifier,
for:indexPath) as! VDrawProjectMenuEditBarCell
cell.config(model:item)
return cell
}
func collectionView(_ collectionView:UICollectionView, didSelectItemAt indexPath:IndexPath)
{
collectionView.isUserInteractionEnabled = false
let item:MDrawProjectMenuEditBarItem = modelAtIndex(index:indexPath)
item.selected(controller:controller)
DispatchQueue.main.asyncAfter(
deadline:DispatchTime.now() + kDeselectTime)
{ [weak collectionView] in
collectionView?.selectItem(
at:nil,
animated:true,
scrollPosition:UICollectionViewScrollPosition())
collectionView?.isUserInteractionEnabled = true
}
}
}
| c649081a82cfb7dbdedb69840f7b21d1 | 31.666667 | 155 | 0.658418 | false | false | false | false |
byvapps/ByvManager-iOS | refs/heads/master | ByvManager/Classes/Device.swift | mit | 1 | //
// Device.swift
// Pods
//
// Created by Adrian Apodaca on 24/10/16.
//
//
import Foundation
import Alamofire
import SwiftyJSON
public struct Device {
public static var autoResetBadge = true
var deviceId: String?
var uid: String
var name: String?
var os: String
var osVersion: String
var device: String
var manufacturer: String
var model: String
var appVersion: String?
var appVersionCode: String?
var createdAt: Date?
var updatedAt: Date?
var active: Bool
var lastConnectionStart: Date?
var lastConnectionEnd: Date?
var pushId: String?
var badge: Int
var languageCode: String?
var preferredLang: String?
var countryCode: String?
var regionCode: String?
var currencyCode: String?
var timezone: String?
// MARK: - init
//
// Init device. If stored get static data from Defaults, else get uid
//
public init() {
var jsonStr:String = ""
if let str = UserDefaults.standard.string(forKey: "deviceJsonData") {
jsonStr = str
}
let stored = JSON(parseJSON: jsonStr)
if let id = stored["_id"].string {
self.deviceId = id
}
if let uid = stored["uid"].string {
self.uid = uid
} else {
self.uid = ByvKeychainManager.sharedInstance.getDeviceIdentifierFromKeychain()
}
if let active = stored["active"].int{
self.active = active == 1
} else {
self.active = true
}
if let badge = stored["badge"].int {
self.badge = badge
} else {
self.badge = 0
}
if let pushId = stored["pushId"].string {
self.pushId = pushId
}
if let preferredLang = stored["preferredLang"].string {
self.preferredLang = preferredLang
}
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
if let createdAt = stored["createdAt"].string {
self.createdAt = formatter.date(from: createdAt)
}
if let updatedAt = stored["updatedAt"].string {
self.updatedAt = formatter.date(from: updatedAt)
}
if let lastConnectionStart = stored["lastConnectionStart"].string {
self.lastConnectionStart = formatter.date(from: lastConnectionStart)
}
if let lastConnectionEnd = stored["lastConnectionEnd"].string {
self.lastConnectionEnd = formatter.date(from: lastConnectionEnd)
}
name = UIDevice.current.name
os = "iOS"
osVersion = UIDevice.current.systemVersion
device = UIDevice.current.model
manufacturer = "Apple"
model = UIDevice.current.localizedModel
appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
appVersionCode = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
languageCode = Locale.current.languageCode
countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String
regionCode = Locale.current.regionCode
currencyCode = Locale.current.currencyCode
timezone = TimeZone.current.identifier
}
// MARK: - private
//
// create or update in server
//
private func storeInServer() {
var params: Params = self.parameters()
if Device.autoResetBadge {
params["badge"] = NSNumber(integerLiteral: 0)
UIApplication.shared.applicationIconBadgeNumber = 0
}
var path: String
var method: HTTPMethod
if let deviceId = self.deviceId {
method = .put
path = "\(url_devices())/\(deviceId)"
} else {
method = .post
path = url_devices()
}
ConManager.connection(path,
params: params,
method: method,
encoding: JSONEncoding.default,
success: { (responseData) in
if let data: Data = responseData?.data {
do {
let json = try JSON(data: data)
self.store(json)
} catch {
}
}
})
}
//
// convert Device to Parameters
//
private func parameters() -> Parameters {
var response: Parameters = Parameters()
if let name = self.name {
response["name"] = name
}
response["uid"] = uid
response["active"] = active
if let pushId = self.pushId {
response["pushId"] = pushId
}
response["badge"] = badge
response["os"] = os
response["osVersion"] = osVersion
response["device"] = device
response["manufacturer"] = manufacturer
response["model"] = model
if let appVersion = self.appVersion {
response["appVersion"] = appVersion
}
if let appVersionCode = self.appVersionCode {
response["appVersionCode"] = appVersionCode
}
if let languageCode = self.languageCode {
response["languageCode"] = languageCode
}
if let preferredLang = self.preferredLang {
response["preferredLang"] = preferredLang
}
if let countryCode = self.countryCode {
response["countryCode"] = countryCode
}
if let regionCode = self.regionCode {
response["regionCode"] = regionCode
}
if let currencyCode = self.currencyCode {
response["currencyCode"] = currencyCode
}
if let timezone = self.timezone {
response["timezone"] = timezone
}
return response
}
private func store(_ json: JSON?) {
if json?["_id"].string != nil {
let defs = UserDefaults.standard
defs.set(json?.rawString(), forKey: "deviceJsonData")
defs.synchronize()
} else {
print("Error storing device Json")
}
}
// MARK: - public static
public static func setDeviceActive(_ active: Bool) {
var device = Device()
device.active = active
device.badge = 0
device.storeInServer()
}
public static func setPushId(_ pushId: String) {
var device = Device()
device.pushId = pushId
device.storeInServer()
}
}
| 2c057c83e79f239c7a8c2a44ce1fbd69 | 29.411504 | 90 | 0.535865 | false | false | false | false |
moked/iuob | refs/heads/master | iUOB 2/Controllers/CoursesVC.swift | mit | 1 | //
// CoursesVC.swift
// iUOB 2
//
// Created by Miqdad Altaitoon on 8/10/16.
// Copyright © 2016 Miqdad Altaitoon. All rights reserved.
//
import UIKit
import Alamofire
import MBProgressHUD
class CoursesVC: UITableViewController {
// MARK: - Properties
var department:Department!
var courses: [Course] = []
// MARK: - Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
googleAnalytics()
self.title = department.name
getCourses()
}
func googleAnalytics() {
if let tracker = GAI.sharedInstance().defaultTracker {
tracker.set(kGAIScreenName, value: NSStringFromClass(type(of: self)).components(separatedBy: ".").last!)
let builder: NSObject = GAIDictionaryBuilder.createScreenView().build()
tracker.send(builder as! [NSObject : AnyObject])
}
}
// MARK: - Load Data
func getCourses() {
MBProgressHUD.showAdded(to: self.view, animated: true)
Alamofire.request(department.url, parameters: nil)
.validate()
.responseString { response in
MBProgressHUD.hide(for: self.view, animated: true)
if response.result.error == nil {
self.courses = UOBParser.parseCourses(response.result.value!)
self.tableView.reloadData()
} else {
print("error man")
}
}
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return courses.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CourseCell", for: indexPath)
cell.textLabel?.text = "\(courses[(indexPath as NSIndexPath).row].code) - \(courses[(indexPath as NSIndexPath).row].name)"
cell.detailTextLabel?.text = courses[(indexPath as NSIndexPath).row].preRequisite
return cell
}
// Mark: Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowTiming" {
let indexPath = self.tableView.indexPath(for: sender as! UITableViewCell)! as IndexPath
let destinationViewController = segue.destination as! TimingVC
destinationViewController.course = courses[(indexPath as NSIndexPath).row]
}
}
}
| fb6a31877753cee2f130838b870df278 | 29.280899 | 130 | 0.588868 | false | false | false | false |
hacktoolkit/hacktoolkit-ios_lib | refs/heads/master | Hacktoolkit/lib/GitHub/models/GitHubOrganization.swift | mit | 1 | //
// GitHubOrganization.swift
//
// Created by Hacktoolkit (@hacktoolkit) and Jonathan Tsai (@jontsai)
// Copyright (c) 2014 Hacktoolkit. All rights reserved.
//
import Foundation
protocol GitHubOrganizationDelegate {
func didFinishFetching()
}
class GitHubOrganization: GitHubResource {
var delegate: GitHubOrganizationDelegate?
// https://developer.github.com/v3/orgs/
let GITHUB_ORGANIZATION_RESOURCE_BASE = "/orgs/"
// meta
var handle: String
// Organization attributes
var login: String!
var id: Int!
var url: String!
var avatarUrl: String!
var name: String!
var company: String!
var blog: String!
var location: String!
var email: String!
var publicRepos: Int!
var publicGists: Int!
var followers: Int!
var following: Int!
var htmlURL: String!
// Organization relations
lazy var repositories: [GitHubRepository] = [GitHubRepository]()
init(name: String, onInflated: ((GitHubResource) -> ())? = nil) {
self.handle = name
super.init(onInflated)
}
init(fromDict organizationDict: NSDictionary) {
self.handle = ""
super.init()
inflater(organizationDict as AnyObject)
}
override func getResourceURL() -> String {
var resource = "\(GITHUB_ORGANIZATION_RESOURCE_BASE)\(self.handle)"
return resource
}
override func inflater(result: AnyObject) {
var resultJSON = result as NSDictionary
self.login = resultJSON["login"] as? String
self.id = resultJSON["id"] as? Int
self.url = resultJSON["url"] as? String
self.avatarUrl = resultJSON["avatar_url"] as? String
self.name = resultJSON["name"] as? String
self.company = resultJSON["company"] as? String
self.blog = resultJSON["blog"] as? String
self.location = resultJSON["location"] as? String
self.email = resultJSON["email"] as? String
self.publicRepos = resultJSON["publicRepos"] as? Int
self.publicGists = resultJSON["publicGists"] as? Int
self.followers = resultJSON["followers"] as? Int
self.following = resultJSON["following"] as? Int
self.htmlURL = resultJSON["htmlURL"] as? String
super.inflater(resultJSON)
}
func getRepositories(onInflated: ([GitHubRepository]) -> ()) {
var resource = "\(self.getResourceURL())/repos"
GitHubClient.sharedInstance.makeApiRequest(resource, callback: {
(results: AnyObject) -> () in
var resultsJSONArray = results as? [NSDictionary]
if resultsJSONArray != nil {
var repositories = resultsJSONArray!.map {
(repositoryDict: NSDictionary) -> GitHubRepository in
GitHubRepository(repositoryDict: repositoryDict)
}
self.repositories = repositories
if self.delegate != nil {
self.delegate!.didFinishFetching()
}
} else {
HTKNotificationUtils.displayNetworkErrorMessage()
}
})
}
}
//{
// "login": "github",
// "id": 1,
// "url": "https://api.github.com/orgs/github",
// "avatar_url": "https://github.com/images/error/octocat_happy.gif",
// "name": "github",
// "company": "GitHub",
// "blog": "https://github.com/blog",
// "location": "San Francisco",
// "email": "[email protected]",
// "public_repos": 2,
// "public_gists": 1,
// "followers": 20,
// "following": 0,
// "html_url": "https://github.com/octocat",
// "created_at": "2008-01-14T04:33:35Z",
// "type": "Organization"
//}
| 2b8508ab6990da20c5a15685cf18d67d | 30.504274 | 75 | 0.606891 | false | false | false | false |
jmgc/swift | refs/heads/master | test/Constraints/async.swift | apache-2.0 | 1 | // RUN: %target-typecheck-verify-swift -enable-experimental-concurrency
// REQUIRES: concurrency
func doAsynchronously() async { }
func doSynchronously() { }
func testConversions() async {
let _: () -> Void = doAsynchronously // expected-error{{invalid conversion from 'async' function of type '() async -> ()' to synchronous function type '() -> Void'}}
let _: () async -> Void = doSynchronously // okay
}
// Overloading
@available(swift, deprecated: 4.0, message: "synchronous is no fun")
func overloadedSame(_: Int = 0) -> String { "synchronous" }
func overloadedSame() async -> String { "asynchronous" }
func overloaded() -> String { "synchronous" }
func overloaded() async -> Double { 3.14159 }
@available(swift, deprecated: 4.0, message: "synchronous is no fun")
func overloadedOptDifference() -> String { "synchronous" }
func overloadedOptDifference() async -> String? { nil }
func testOverloadedSync() {
_ = overloadedSame() // expected-warning{{synchronous is no fun}}
let _: String? = overloadedOptDifference() // expected-warning{{synchronous is no fun}}
let _ = overloaded()
let fn = {
overloaded()
}
let _: Int = fn // expected-error{{value of type '() -> String'}}
let fn2 = {
print("fn2")
_ = overloaded()
}
let _: Int = fn2 // expected-error{{value of type '() -> ()'}}
let fn3 = {
await overloaded()
}
let _: Int = fn3 // expected-error{{value of type '() async -> Double'}}
let fn4 = {
print("fn2")
_ = await overloaded()
}
let _: Int = fn4 // expected-error{{value of type '() async -> ()'}}
}
func testOverloadedAsync() async {
_ = await overloadedSame() // no warning
let _: String? = await overloadedOptDifference() // no warning
let _ = await overloaded()
let _ = overloaded() // expected-error{{call is 'async' but is not marked with 'await'}}{{11-11=await }}
let fn = {
overloaded()
}
let _: Int = fn // expected-error{{value of type '() -> String'}}
let fn2 = {
print("fn2")
_ = overloaded()
}
let _: Int = fn2 // expected-error{{value of type '() -> ()'}}
let fn3 = {
await overloaded()
}
let _: Int = fn3 // expected-error{{value of type '() async -> Double'}}
let fn4 = {
print("fn2")
_ = await overloaded()
}
let _: Int = fn4 // expected-error{{value of type '() async -> ()'}}
}
func takesAsyncClosure(_ closure: () async -> String) -> Int { 0 }
func takesAsyncClosure(_ closure: () -> String) -> String { "" }
func testPassAsyncClosure() {
let a = takesAsyncClosure { await overloadedSame() }
let _: Double = a // expected-error{{convert value of type 'Int'}}
let b = takesAsyncClosure { overloadedSame() } // expected-warning{{synchronous is no fun}}
let _: Double = b // expected-error{{convert value of type 'String'}}
}
struct FunctionTypes {
var syncNonThrowing: () -> Void
var syncThrowing: () throws -> Void
var asyncNonThrowing: () async -> Void
var asyncThrowing: () async throws -> Void
mutating func demonstrateConversions() {
// Okay to add 'async' and/or 'throws'
asyncNonThrowing = syncNonThrowing
asyncThrowing = syncThrowing
syncThrowing = syncNonThrowing
asyncThrowing = asyncNonThrowing
// Error to remove 'async' or 'throws'
syncNonThrowing = asyncNonThrowing // expected-error{{invalid conversion}}
syncThrowing = asyncThrowing // expected-error{{invalid conversion}}
syncNonThrowing = syncThrowing // expected-error{{invalid conversion}}
asyncNonThrowing = syncThrowing // expected-error{{invalid conversion}}
}
}
| b80e528f73c69da85f9634ed5a3c4ae3 | 29.606838 | 167 | 0.643675 | false | false | false | false |
lemberg/obd2-swift-lib | refs/heads/master | OBD2-Swift/Classes/Common/Macros.swift | mit | 1 | //
// Macros.swift
// OBD2Swift
//
// Created by Max Vitruk on 08/06/2017.
// Copyright © 2017 Lemberg. All rights reserved.
//
import Foundation
//------------------------------------------------------------------------------
// Macros
// Macro to test if a given PID, when decoded, is an
// alphanumeric string instead of a numeric value
func IS_ALPHA_VALUE(pid : UInt8) -> Bool{
return (pid == 0x03 || pid == 0x12 || pid == 0x13 || pid == 0x1C || pid == 0x1D || pid == 0x1E)
}
// Macro to test if a given PID has two measurements in the returned data
func IS_MULTI_VALUE_SENSOR(pid : UInt8) -> Bool {
return (pid >= 0x14 && pid <= 0x1B) ||
(pid >= 0x24 && pid <= 0x2B) ||
(pid >= 0x34 && pid <= 0x3B)
}
func IS_INT_VALUE(pid : Int8, sensor : OBD2Sensor) -> Bool {
return (pid >= 0x04 && pid <= 0x13) ||
(pid >= 0x1F && pid <= 0x23) ||
(pid >= 0x2C && pid <= 0x33) ||
(pid >= 0x3C && pid <= 0x3F) ||
(pid >= 0x43 && pid <= 0x4E) ||
(pid >= 0x14 && pid <= 0x1B && sensor.rawValue == 0x02) ||
(pid >= 0x24 && pid <= 0x2B && sensor.rawValue == 0x02) ||
(pid >= 0x34 && pid <= 0x3B && sensor.rawValue == 0x02)
}
func MORE_PIDS_SUPPORTED(_ data : [UInt8]) -> Bool {
guard data.count > 3 else {return false}
return ((data[3] & 1) != 0)
}
func NOT_SEARCH_PID(_ pid : Int) -> Bool {
return (pid != 0x00 && pid != 0x20 &&
pid != 0x40 && pid != 0x60 &&
pid != 0x80 && pid != 0xA0 &&
pid != 0xC0 && pid != 0xE0)
}
let kCarriageReturn = "\r"
let DTC_SYSTEM_MASK : UInt8 = 0xC0
let DTC_DIGIT_0_1_MASK : UInt8 = 0x3F
let DTC_DIGIT_2_3_MASK : UInt8 = 0xFF
| 255196c8f235f524cb23063b4db3b021 | 28.4 | 97 | 0.539889 | false | false | false | false |
liusally/SLCarouselView | refs/heads/master | Examples/SLCarouselViewExample/SLCarouselViewExample/ViewController.swift | mit | 1 | //
// ViewController.swift
// SLCarouselViewExample
//
// Created by Shali Liu on 7/19/17.
// Copyright © 2017 Shali Liu. All rights reserved.
//
import UIKit
import AVFoundation
import SDWebImage
import SLCarouselView
class ViewController: UIViewController {
@IBOutlet var carouselView: SLCarouselView!
fileprivate var playerArr = [AVPlayer?]()
override func viewDidLoad() {
super.viewDidLoad()
// Data examples
let data: [Dictionary<String, String>] = [
["type": "image", "url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/20065243_243723416143011_6663416918206054400_n.jpg"],
["type": "image", "url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19984908_462044610837470_639420776679735296_n.jpg"],
["type": "image", "url": "https://scontent.cdninstagram.com/t51.2885-15/s640x640/sh0.08/e35/19955017_1738275873137290_7355135153712136192_n.jpg"],
["type": "video", "url": "https://scontent.cdninstagram.com/t50.2886-16/19179996_870131086458262_8352073221473828864_n.mp4"]
]
setupCarouselView(data: data)
}
private func setupCarouselView(data: [Dictionary<String, String>]) {
for index in 0...(data.count - 1) {
let item = data[index]
if (item["type"] == "image") {
// image
let imageUrl = item["url"]
let imageSlide = UIImageView()
imageSlide.contentMode = UIViewContentMode.scaleAspectFill
imageSlide.clipsToBounds = true
imageSlide.sd_setImage(with: URL(string: imageUrl!))
self.carouselView.appendContent(view: imageSlide)
}
if (item["type"] == "video") {
// video
let videoView = UIView()
self.carouselView.appendContent(view: videoView)
let videoUrl = item["url"]
let player = AVPlayer(url: URL(string: videoUrl!)!)
self.playerArr.append(player)
// Mute video
player.volume = 0
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = videoView.bounds
videoView.layer.addSublayer(playerLayer)
// Resize video to frame
playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
// Loop playing video
NotificationCenter.default.addObserver(self, selector: #selector(self.loopPlayVideo), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: player.currentItem)
player.play()
}
}
}
func loopPlayVideo() {
for player in self.playerArr {
player?.seek(to: kCMTimeZero)
player?.play()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 7ad03e6c7481d2e2210828db8ec7cb99 | 34.417582 | 185 | 0.568415 | false | false | false | false |
Ellestad1995/supreme-invention | refs/heads/master | selectiveCollectionView/selectiveCollectionView/collView.swift | mit | 1 | //
// collView.swift
// selectiveCollectionView
//
// Created by Joakim Nereng Ellestad on 05.01.2017.
// Copyright © 2017 Joakim Ellestad. All rights reserved.
//
import UIKit
class collView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
self.setupCollectionView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
//fatalError("init(coder:) has not been implemented")
}
override func draw(_ rect: CGRect) {
//self.setupCollectionView()
}
override func layoutSubviews() {
super.layoutSubviews()
//add shadow
self.layer.shadowColor = UIColor.black.cgColor
self.layer.masksToBounds = false
self.clipsToBounds = true
self.layer.shadowOpacity = 0.5
self.layer.shadowRadius = 3.0
self.layer.shouldRasterize = false
self.layer.shadowOffset = CGSize(width: 0, height: 1)
self.layer.shadowPath = UIBezierPath(rect: self.layer.bounds).cgPath
}
func setupCollectionView(){
//setup the class
self.showsVerticalScrollIndicator = false
self.backgroundColor = UIColor.white
self.allowsSelection = false
self.translatesAutoresizingMaskIntoConstraints = false
//registering two cells
self.register(newcell.self, forCellWithReuseIdentifier: "newcell")
self.register(defaultcell.self, forCellWithReuseIdentifier: "defaultcell")
}
}
| 213647e328f3913b44629b86fbb8ceda | 28.314815 | 87 | 0.676563 | false | false | false | false |
andreyvit/ExpressiveFoundation.swift | refs/heads/master | Source/ExpressiveEvents/Event.swift | mit | 1 | //
// ExpressiveEvents, part of ExpressiveSwift project
//
// Copyright (c) 2014-2015 Andrey Tarantsov <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
/**
An event that can be emitted by `EmitterType`s.
In the simplest case, an event can be an empty struct. You can even declare it within the relevant class:
```
class Foo: StdEmitterType {
struct SomethingDidHappen: EventType {
}
func doSomething() {
emit(SomethingDidHappen())
}
var _listeners = EventListenerStorage()
}
func test() {
var o = Observation()
var foo = Foo()
o += foo.subscribe { (event: SomethingDidHappen, emitter) in
print("did happen")
}
foo.doSomething() // prints "did happen"
}
```
You may want to add additional details:
```
struct SomethingDidHappen: EventType {
let reason: String
}
class Foo: StdEmitterType {
func doSomething() {
emit(SomethingDidHappen("no reason at all"))
}
var _listeners = EventListenerStorage()
}
func test() {
var o = Observation()
var foo = Foo()
o += foo.subscribe { (event: SomethingDidHappen, emitter) in
print("did happen for \(event.reason)")
}
foo.doSomething() // prints "did happen for no reason at all"
}
```
An event can also be a class. For example, this may be useful if you want the event handlers to be able to return a value:
```
class SomethingWillHappen: EventType {
var allow: Bool = true
}
class Foo: StdEmitterType {
func doSomething() {
let event = SomethingWillHappen()
emit(event)
if event.allow {
print("actually doing it")
} else {
print("forbidden")
}
}
var _listeners = EventListenerStorage()
}
func test() {
var o = Observation()
var foo = Foo()
o += foo.subscribe { (event: SomethingWillHappen, emitter) in
event.allow = false
}
foo.doSomething() // prints "forbidden"
}
```
*/
public protocol EventType {
}
public extension EventType {
/// The name of the event for debugging and logging purposes. This returns a fully qualified type name like `MyModule.Foo.SomethingDidHappen`.
public static var eventName: String {
return String(reflecting: self)
}
public var eventName: String {
return self.dynamicType.eventName
}
}
/**
An event that can be posted via `NSNotificationCenter`.
*/
public protocol EventTypeWithNotification: EventType {
/// The notification center event name. By default this returns `eventName`, which is a fully qualified type name.
static var notificationName: String { get }
var notificationUserInfo: [String: AnyObject] { get }
}
public extension EventTypeWithNotification {
static var notificationName: String {
return eventName
}
var notificationUserInfo: [String: AnyObject] {
return [:]
}
}
| 63edab2321fe985ac6e773dab1d3a2f6 | 27.304965 | 146 | 0.67978 | false | false | false | false |
smoope/ios-sdk | refs/heads/master | Pod/Classes/SPMessage.swift | apache-2.0 | 1 | /*
* Copyright 2016 smoope GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
public class SPMessage: SPCreated {
public var parts: [Part] = []
public init(parts: [Part]) {
self.parts = parts
super.init()
}
public required init(data: [String: AnyObject]) {
if let parts = data["_embedded"]!["parts"] as? [AnyObject] {
self.parts = parts
.map { v in
Part(data: v as! [String: AnyObject])
}
}
super.init(data: data)
}
public override func unmap() -> [String: AnyObject] {
var result: [String: AnyObject] = [:]
if !parts.isEmpty {
result["parts"] = parts.map({ part in part.unmap() })
}
return result
.append(super.unmap())
}
public class Part: SPBase {
private var mimeType: String
private var encoding: String?
private var body: String?
private var filename: String?
private var url: String?
private init(mimeType: String, encoding: String? = nil, body: String? = nil, filename: String? = nil, url: String? = nil) {
self.mimeType = mimeType
self.encoding = encoding
self.body = body
self.filename = filename
self.url = url
super.init()
}
public required init(data: Dictionary<String, AnyObject>) {
self.mimeType = data["mimeType"] as! String
if let encoding = data["encoding"] {
self.encoding = encoding as? String
}
if let body = data["body"] {
self.body = body as? String
}
if let filename = data["filename"] {
self.filename = filename as? String
}
super.init(data: data)
}
public override func unmap() -> [String: AnyObject] {
var result: [String: AnyObject] = ["mimeType": mimeType]
if let encoding = self.encoding {
result["encoding"] = encoding
}
if let body = self.body {
result["body"] = body
}
if let filename = self.filename {
result["filename"] = filename
}
if let url = self.url {
result["url"] = url
}
return result
.append(super.unmap())
}
public static func text(text: String) -> Part {
return Part(mimeType: "text/plain", body: text)
}
public static func media(mimeType: String, filename: String, url: String) -> Part {
return Part(mimeType: mimeType, filename: filename, url: url)
}
}
} | 990b0acddcb14f8448ec001b5f01ad05 | 25.359649 | 127 | 0.6002 | false | false | false | false |
vmachiel/swift | refs/heads/main | LearningSwift.playground/Pages/Operators.xcplaygroundpage/Contents.swift | mit | 1 | // Basic operators:
var a = 10
a = a + 1
a = a - 1
a = a * 2
a = a / 2
var b = 13 / 3 // floor devision, won't do float automatically because strong typing!
b = b % 3 // modulus or remain
// Like python, you can shorten the x = x + 10 thing
b = 10
b += 10
b -= 10
// adding doubles
var c = 1.1
var d = 2.2
var e = c + d
// String concatination
var name1 = "Machiel van Dorst"
var name2 = "Annabel Dellebeke"
var bothNames = name1 + " en " + name2
// comparison operators that return Booleans:
e > 3
e < 3
e <= 3
e >= 3
e == 3
e != 3
name1 == "Machiel van Dorst" // true!
// Use the ! operator before any Boolean to flip it:
var stayOutTooLate = true // true
!stayOutTooLate // false
// or and operators:
stayOutTooLate && true
!stayOutTooLate && true
stayOutTooLate || true
!stayOutTooLate || true
// Interpolation: basically python f-strings. Do in place calculations and manipulation of
// variables and convert them into String, and print out the whole thing.
// More efficient than concatinating, and allows for calculations
var name = "Machiel van Dorst"
"Your name is \(name)"
// Another example:
var age = 29
var latitude = 51.16643
print("Your name is \(name) and your age is \(age) and you're at latitude \(latitude)")
print("In three years time, you'll be \(age + 3) years old")
// Array operation:
var songs = ["Shake it Off", "You Belong with Me", "Back to December"]
var songs2 = ["Today was a Fairytale", "Welcome to New York", "Fifteen"]
var both = songs + songs2
songs += ["Snorsex"]
// Ternary operator: Assign something if to var or constant if expression is true
// or false. If true, assign what is before after ?, else assign what is after :
let currentWeather = "Sunny"
let currentMood = currentWeather == "Sunny" ? "Happy" : "Cranky" // Happy
// Comparing tuples:
(1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple" are not compared
(3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less than "bird"
(4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog'
let firstName = "Paul"
let secondName = "Sophie"
print(firstName == secondName)
print(firstName != secondName)
print(firstName < secondName)
print(firstName >= secondName)
| 4587e6d3c918d23efbe3a74eaf935695 | 24.806818 | 100 | 0.67151 | false | false | false | false |
migchaves/SwiftCoreData | refs/heads/master | Swift CoreData Example/DataBase/DBManager.swift | mit | 1 | //
// DBManager.swift
// Swift CoreData Example
//
// Created by Miguel Chaves on 19/01/16.
// Copyright © 2016 Miguel Chaves. All rights reserved.
//
import UIKit
import CoreData
class DBManager: NSObject {
// MARK: - Class Properties
var managedObjectContext: NSManagedObjectContext
var managedObjectModel: NSManagedObjectModel
var persistentStoreCoordinator: NSPersistentStoreCoordinator
// MARK: - Init class
override init() {
self.managedObjectModel = NSManagedObjectModel.init(contentsOfURL: DBManager.getModelUrl())!
self.persistentStoreCoordinator = NSPersistentStoreCoordinator.init(managedObjectModel: self.managedObjectModel)
do {
try self.persistentStoreCoordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil,
URL: DBManager.storeURL(), options: nil)
} catch let error as NSError {
print(error)
abort()
}
self.managedObjectContext = NSManagedObjectContext.init(concurrencyType: .MainQueueConcurrencyType)
self.managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator
self.managedObjectContext.mergePolicy = NSOverwriteMergePolicy
}
// MARK: - Shared Instance
class var sharedInstance: DBManager {
struct Singleton {
static let instance = DBManager()
}
return Singleton.instance
}
// MARK: - Create and Save objects
func managedObjectOfType(objectType: String) -> NSManagedObject {
let newObject = NSEntityDescription.insertNewObjectForEntityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
return newObject
}
func temporaryManagedObjectOfType(objectType: String) -> NSManagedObject {
let description = NSEntityDescription.entityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
let temporaryObject = NSManagedObject.init(entity: description!,
insertIntoManagedObjectContext: nil)
return temporaryObject
}
func insertManagedObject(object: NSManagedObject) {
self.managedObjectContext.insertObject(object)
saveContext()
}
func saveContext() {
if (!self.managedObjectContext.hasChanges) {
return
} else {
do {
try self.managedObjectContext.save()
} catch let exception as NSException {
print("Error while saving \(exception.userInfo) : \(exception.reason)")
} catch {
print("Error while saving data!")
}
}
}
// MARK: - Retrieve data
func allEntriesOfType(objectType: String) -> [AnyObject] {
let entety = NSEntityDescription.entityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
let request = NSFetchRequest.init()
request.entity = entety
request.includesPendingChanges = true
do {
let result = try self.managedObjectContext.executeFetchRequest(request)
return result
} catch {
print("Error executing request in the Data Base.")
}
return []
}
func getEntryOfType(objectType: String, propertyName: String, propertyValue: AnyObject) -> [AnyObject] {
let entety = NSEntityDescription.entityForName(objectType,
inManagedObjectContext: self.managedObjectContext)
let request = NSFetchRequest.init()
request.entity = entety
request.includesPendingChanges = true
let predicate = NSPredicate(format: "\(propertyName) == \(propertyValue)")
request.predicate = predicate
do {
let result = try self.managedObjectContext.executeFetchRequest(request)
var returnArray: [AnyObject] = [AnyObject]()
for element in result {
returnArray.append(element)
}
return returnArray
} catch {
print("Error executing request in the Data Base")
}
return []
}
func deleteAllEntriesOfType(objectType: String) {
let elements = allEntriesOfType(objectType)
if (elements.count > 0) {
for element in elements {
self.managedObjectContext.deleteObject(element as! NSManagedObject)
}
saveContext()
}
}
func deleteObject(object: NSManagedObject) {
self.managedObjectContext.deleteObject(object)
saveContext()
}
// MARK: - Private functions
static private func getModelUrl() -> NSURL {
return NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
}
static private func storeURL () -> NSURL? {
let applicationDocumentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last
let storeUrl = applicationDocumentsDirectory?.URLByAppendingPathComponent("Model.sqlite")
return storeUrl
}
}
| c5d82919842c61aea567d350494be5ae | 31.149701 | 144 | 0.623207 | false | false | false | false |
VinlorJiang/DouYuWL | refs/heads/master | DouYuWL/DouYuWL/Classes/Main/ViewModel/BaseViewModel.swift | mit | 1 | //
// BaseViewModel.swift
// DouYuWL
//
// Created by dinpay on 2017/7/24.
// Copyright © 2017年 apple. All rights reserved.
//
import UIKit
class BaseViewModel {
lazy var anchorGroupModels : [AnchorGroupModel] = [AnchorGroupModel]()
}
extension BaseViewModel {
func loadAnchorData(isGroupData : Bool, URLString : String, parameters : [String : Any]? = nil, finishedCallback : @escaping () -> ()) {
NetWorkTools.requestData(.get, URLString: URLString, parameters: parameters) { (result) in
// 1.对界面进行处理
guard let resultDic = result as? [String : Any] else { return }
guard let dataArray = resultDic["data"] as? [[String : Any]] else { return }
// 2.判断是否分组数据
if isGroupData {
// 2.1.遍历数组中的字典
for dic in dataArray {
self.anchorGroupModels.append(AnchorGroupModel(dict:dic))
}
} else {
// 2.1.创建组
let group = AnchorGroupModel()
// 2.2.遍历dataArray的所有的字典
for dic in dataArray {
group.anchors.append(AnchorModel(dict : dic))
}
// 2.3.将group,添加到anchorGroups
self.anchorGroupModels.append(group)
}
// 3.完成回调
finishedCallback()
}
}
}
| ee5af1d147f1ec00cb4b9aa9aadd863d | 31.857143 | 140 | 0.536957 | false | false | false | false |
DanisFabric/RainbowNavigation | refs/heads/master | RainbowNavigation/UINavigationBar+Rainbow.swift | mit | 1 | //
// UINavigationBar+Rainbow.swift
// Pods
//
// Created by Danis on 15/11/25.
//
//
import Foundation
private var kRainbowAssociatedKey = "kRainbowAssociatedKey"
public class Rainbow: NSObject {
var navigationBar: UINavigationBar
init(navigationBar: UINavigationBar) {
self.navigationBar = navigationBar
super.init()
}
fileprivate var navigationView: UIView?
fileprivate var statusBarView: UIView?
public var backgroundColor: UIColor? {
get {
return navigationView?.backgroundColor
}
set {
if navigationView == nil {
navigationBar.setBackgroundImage(UIImage(), for: .default)
navigationBar.shadowImage = UIImage()
navigationView = UIView(frame: CGRect(x: 0, y: -UIApplication.shared.statusBarFrame.height, width: navigationBar.bounds.width, height: navigationBar.bounds.height + UIApplication.shared.statusBarFrame.height))
navigationView?.isUserInteractionEnabled = false
navigationView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
navigationBar.insertSubview(navigationView!, at: 0)
}
navigationView!.backgroundColor = newValue
}
}
public var statusBarColor: UIColor? {
get {
return statusBarView?.backgroundColor
}
set {
if statusBarView == nil {
statusBarView = UIView(frame: CGRect(x: 0, y: -UIApplication.shared.statusBarFrame.height, width: navigationBar.bounds.width, height: UIApplication.shared.statusBarFrame.height))
statusBarView?.isUserInteractionEnabled = false
statusBarView?.autoresizingMask = [.flexibleWidth, .flexibleHeight]
if let navigationView = navigationView {
navigationBar.insertSubview(statusBarView!, aboveSubview: navigationView)
} else {
navigationBar.insertSubview(statusBarView!, at: 0)
}
}
statusBarView?.backgroundColor = newValue
}
}
public func clear() {
navigationBar.setBackgroundImage(nil, for: .default)
navigationBar.shadowImage = nil
navigationView?.removeFromSuperview()
navigationView = nil
statusBarView?.removeFromSuperview()
statusBarView = nil
}
}
extension UINavigationBar {
public var rb: Rainbow {
get {
if let rainbow = objc_getAssociatedObject(self, &kRainbowAssociatedKey) as? Rainbow {
return rainbow
}
let rainbow = Rainbow(navigationBar: self)
objc_setAssociatedObject(self, &kRainbowAssociatedKey, rainbow, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return rainbow
}
}
}
| 0a890ac83d165b4cef9d9665f86b0465 | 34.158537 | 225 | 0.621922 | false | false | false | false |
SpiciedCrab/CodingForP | refs/heads/master | CodingForP_Sample/CodingForP_Sample/SampleViewModel.swift | mit | 1 | //
// SampleViewModel.swift
// CodingForP_Sample
//
// Created by Harly on 2017/2/6.
// Copyright © 2017年 MogoOrg. All rights reserved.
//
import UIKit
class SampleViewModel: NSObject {
func samplePlist()
{
let sampleSource = ["userName" : "harly", "userId" : "123", "price" : "99222"]
guard let plistPath = Bundle.main.path(forResource: "sampleCodingP", ofType: "plist") else { return }
guard let value = NSArray(contentsOfFile: plistPath)!.firstObject as? String else { return }
print("\(smartTranslate(value, fromLazyServerJson: sampleSource))")
}
func setupData() -> [String : Any]
{
let sampleSource = ["id" : "10000", "name" : "Fish", "salary" : 5000 , "summary" : "fff", "description" : "sss"] as [String : Any]
let person = Person(json : sampleSource)
return ["Name" : person.name,
"price" : person.displayedSalary ,
"Summary" : person.summary ,
"Desciprtion" : person.displayedDiscription]
}
}
func setupData() -> [String : Any]
{
let sampleSource = ["id" : "10000", "name" : "Fish", "salary" : 5000 , "summary" : "fff", "description" : "sss"] as [String : Any]
let person = Person(json : sampleSource)
return ["Name" : person.name,
"Salary" : person.displayedSalary ,
"Summary" : person.summary ,
"Desciprtion" : person.displayedDiscription]
}
struct Person
{
var id : String!
var name : String!
var salary : Double = 0
var summary : String!
var description : String!
var displayedDiscription : String {
return "PersonId : \(id) \n Description : \(description)"
}
var displayedSalary : String {
return currencyGenerator(currencyDoubleValue: salary)
}
func currencyGenerator(currencyDoubleValue : Double) -> String
{
return ""
}
init(json : [String : Any]) {
}
}
struct ConfigRow
{
// left title
var key : String!
// right title
var value : String!
// json中对应的key值
var valuePath : String!
var sortOrder : Int = 0
var color : String = ""
}
| d0195bfacb5e70414848a65117122cba | 24.965116 | 138 | 0.575459 | false | false | false | false |
TheNounProject/CollectionView | refs/heads/main | CollectionView/Layouts/CollectionViewColumnLayout.swift | mit | 1 | //
// CollectionViewLayout.swift
// Lingo
//
// Created by Wesley Byrne on 1/27/16.
// Copyright © 2016 The Noun Project. All rights reserved.
//
import Foundation
/// The delegate for CollectionViewColumnLayout to dynamically customize the layout
@objc public protocol CollectionViewDelegateColumnLayout: CollectionViewDelegate {
// MARK: - Spacing & Insets
/*-------------------------------------------------------------------------------*/
/// Asks the delegate for the number fo columns in a section
///
/// - Parameter collectionView: The collection view
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: A section index
///
/// - Returns: The desired number of columns in the section
@objc optional func collectionView(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
numberOfColumnsInSection section: Int) -> Int
/// Asks the delegate for insets to be applied to content of a given section
///
/// - Parameter collectionView: The collection view
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: A section index
///
/// - Returns: Insets for the section
@objc optional func collectionView(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
insetForSectionAt section: NSInteger) -> NSEdgeInsets
// Between to items in the same column
/// Asks the delegate for the item spacing to be applied to items of the same column of a section
///
/// - Parameter collectionView: The collection view
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: A section index
///
/// - Returns: The desired spacing between items in the same column
@objc optional func collectionView(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
interitemSpacingForSectionAt section: Int) -> CGFloat
/// Asks the delegate for the column spacing to applied to items in a given section
///
/// - Parameter collectionView: The collection view
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: A section index
///
/// - Returns: The desired spacing between columns in the section
@objc optional func collectionview(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
columnSpacingForSectionAt section: Int) -> CGFloat
// MARK: - Item Size
/*-------------------------------------------------------------------------------*/
/// The height for the item at the given indexPath (Priority 2)
///
/// - parameter collectionView: The collection view the item is in
/// - parameter collectionViewLayout: The CollectionViewLayout
/// - parameter indexPath: The indexPath for the item
///
/// - returns: The height for the item
@objc optional func collectionView(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
heightForItemAt indexPath: IndexPath) -> CGFloat
/// The aspect ration for the item at the given indexPath (Priority 1). Width and height must be greater than 0.
///
/// - parameter collectionView: The collection view the item is in
/// - parameter collectionViewLayout: The CollectionViewLayout
/// - parameter indexPath: The indexPath for the item
///
/// - returns: The aspect ration for the item
@objc optional func collectionView(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
aspectRatioForItemAt indexPath: IndexPath) -> CGSize
// MARK: - Header & Footer Size
/*-------------------------------------------------------------------------------*/
/// Asks the delegate for the height of the header in the given section
///
/// - Parameter collectionView: The collection view
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: A section index
/// - Returns: The desired header height or 0 for no header
@objc optional func collectionView(_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
heightForHeaderInSection section: Int) -> CGFloat
/// Asks the delegate for the height of the footer in the given section
///
/// - Parameter collectionView: The collection view
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: A section index
/// - Returns: The desired footer height or 0 for no footer
@objc optional func collectionView (_ collectionView: CollectionView, layout collectionViewLayout: CollectionViewLayout,
heightForFooterInSection section: Int) -> CGFloat
}
/// CollectionViewLayoutElementKind
public struct CollectionViewLayoutElementKind {
public static let SectionHeader: String = "CollectionElementKindSectionHeader"
public static let SectionFooter: String = "CollectionElementKindSectionFooter"
}
extension CollectionViewColumnLayout {
@available(*, deprecated, renamed: "LayoutStrategy")
public typealias ItemRenderDirection = LayoutStrategy
@available(*, deprecated, renamed: "layoutStrategy")
open var itemRenderDirection: LayoutStrategy {
get { return layoutStrategy }
set { self.layoutStrategy = newValue }
}
}
/**
This layout is column based which means you provide the number of columns and cells are placed in the appropriate one. It can be display items all the same size or as a "Pinterest" style layout.
The number of columns can be set dynamically by the delegate or you can provide a default value using `layout.columnCount`.
You can also set the `sectionInsets` and `minimumColumnSpacing` which will affect the width of each column.
With the itemWidth set by the column, you have 3 options to set the height of each item. They are used in the order here. So if aspectRatioForItemAtIndexPath is implemented it is used, otherwise, it checks the next one.
1. aspectRatioForItemAtIndexPath (delegate)
2. heightForItemAtIndexPath (delegate)
3. layout.defaultItemHeight
The delegate method aspectRatioForItemAtIndexPath scales the size of the cell to maintain that ratio while fitting within the caclulated column width.
Mixed use of ratios and heights is also supported. Returning CGSize.zero for a ratio will fall back to the hight. If a valid ratio and height are provided, the height will be appended to the height to respect the ratio. For example, if the column width comes out to 100, a ratio of 2 will determine a height of 200. If a height is also provided by the delegate for the same item, say 20 it will be added, totalling 220.
*/
open class CollectionViewColumnLayout: CollectionViewLayout {
/// The method to use when directing items into columns
///
/// - shortestFirst: Use the current column
/// - leftToRight: Always insert left to right
/// - rightToLeft: Always insert right to left
public enum LayoutStrategy {
case shortestFirst
case leftToRight
case rightToLeft
}
// MARK: - Default layout values
/// The default column count
open var columnCount: NSInteger = 2 { didSet { invalidate() }}
/// The spacing between each column
open var columnSpacing: CGFloat = 8 { didSet { invalidate() }}
/// The vertical spacing between items in the same column
open var interitemSpacing: CGFloat = 8 { didSet { invalidate() }}
/// The height of section header views
open var headerHeight: CGFloat = 0.0 { didSet { invalidate() }}
/// The height of section footer views
open var footerHeight: CGFloat = 0.0 { didSet { invalidate() }}
/// The default height to apply to all items
open var itemHeight: CGFloat = 50 { didSet { invalidate() }}
/// If supplementary views should respect section insets or fill the CollectionView width
open var insetSupplementaryViews: Bool = false { didSet { invalidate() }}
/// If set to true, the layout will invalidate on all bounds changes, if false only on width changes
open var invalidateOnBoundsChange: Bool = false { didSet { invalidate() }}
/// Default insets for all sections
open var sectionInset: NSEdgeInsets = NSEdgeInsets(top: 8, left: 8, bottom: 8, right: 8) { didSet { invalidate() }}
// MARK: - Render Options
/// A hint as to how to render items when deciding which column to place them in
open var layoutStrategy: LayoutStrategy = .leftToRight { didSet { invalidate() }}
// private property and method above.
private weak var delegate: CollectionViewDelegateColumnLayout? { return self.collectionView!.delegate as? CollectionViewDelegateColumnLayout }
private var sections: [SectionAttributes] = []
private class Column {
var frame: CGRect
var height: CGFloat { return items.last?.frame.maxY ?? 0 }
var items: [CollectionViewLayoutAttributes] = []
init(frame: CGRect) {
self.frame = frame
}
func append(item: CollectionViewLayoutAttributes) {
self.items.append(item)
self.frame = self.frame.union(item.frame)
}
}
private class SectionAttributes: CustomStringConvertible {
var frame = CGRect.zero
var contentFrame = CGRect.zero
let insets: NSEdgeInsets
var header: CollectionViewLayoutAttributes?
var footer: CollectionViewLayoutAttributes?
var columns = [Column]()
var items = [CollectionViewLayoutAttributes]()
init(frame: CGRect, insets: NSEdgeInsets) {
self.frame = frame
self.insets = insets
}
func prepareColumns(_ count: Int, spacing: CGFloat, in rect: CGRect) {
self.contentFrame = rect
let y = rect.minY
let gapCount = CGFloat(count-1)
let width = round((rect.width - (gapCount * spacing)) / CGFloat(count))
var x = rect.minX - spacing - width
self.columns = (0..<count).map({ _ -> Column in
x += (spacing + width)
return Column(frame: CGRect(x: x, y: y, width: width, height: 0))
})
}
var description: String {
return "Section Attributes : \(frame) content: \(contentFrame) Items: \(items.count)"
}
func addItem(for indexPath: IndexPath, aspectRatio ratio: CGSize?, variableHeight: CGFloat?, defaultHeight: CGFloat, spacing: CGFloat, strategy: LayoutStrategy) {
let column = self.nextColumnIndexForItem(indexPath, strategy: strategy)
let width = column.frame.size.width
var itemHeight: CGFloat = 0
if let ratio = ratio, ratio.width != 0 && ratio.height != 0 {
let h = ratio.height * (width/ratio.width)
itemHeight = floor(h)
if let addHeight = variableHeight {
itemHeight += addHeight
}
} else {
itemHeight = variableHeight ?? defaultHeight
}
let item = CollectionViewLayoutAttributes(forCellWith: indexPath)
let y = column.frame.maxY + spacing
item.frame = CGRect(x: column.frame.minX, y: y,
width: width, height: itemHeight)
self.items.append(item)
column.append(item: item)
}
func finalizeColumns() {
let cBounds = columns.reduce(CGRect.null) { return $0.union($1.frame) }
self.contentFrame = self.contentFrame.union(cBounds)
self.frame = self.frame.union(self.contentFrame)
}
private func nextColumnIndexForItem(_ indexPath: IndexPath, strategy: LayoutStrategy) -> Column {
switch strategy {
case .shortestFirst :
return columns.min(by: { (c1, c2) -> Bool in
return c1.frame.size.height < c2.frame.size.height
})!
case .leftToRight :
let colCount = self.columns.count
let index = (indexPath._item % colCount)
return self.columns[index]
case .rightToLeft:
let colCount = self.columns.count
let index = (colCount - 1) - (indexPath._item % colCount)
return self.columns[index]
}
}
}
override public init() {
super.init()
}
private var _lastSize = CGSize.zero
override open func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return _lastSize != newBounds.size
}
override open func prepare() {
self.allIndexPaths.removeAll()
self.sections.removeAll()
guard let cv = self.collectionView, cv.numberOfSections > 0 else {
return
}
self._lastSize = cv.frame.size
let numberOfSections = cv.numberOfSections
let contentInsets = cv.contentInsets
var top: CGFloat = self.collectionView?.leadingView?.bounds.size.height ?? 0
for sectionIdx in 0..<numberOfSections {
let colCount: Int = {
let c = self.delegate?.collectionView?(cv, layout: self, numberOfColumnsInSection: sectionIdx) ?? self.columnCount
return max(c, 1)
}()
// 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset)
let sectionInsets = self.delegate?.collectionView?(cv, layout: self, insetForSectionAt: sectionIdx) ?? self.sectionInset
let itemSpacing = self.delegate?.collectionView?(cv, layout: self, interitemSpacingForSectionAt: sectionIdx) ?? self.interitemSpacing
let columnSpacing = self.delegate?.collectionview?(cv, layout: self, columnSpacingForSectionAt: sectionIdx) ?? self.columnSpacing
let contentWidth = cv.contentVisibleRect.size.width - sectionInsets.width
let section = SectionAttributes(frame: CGRect(x: contentInsets.left, y: top, width: contentWidth, height: 0), insets: sectionInsets)
// 2. Section header
let heightHeader: CGFloat = self.delegate?.collectionView?(cv, layout: self, heightForHeaderInSection: sectionIdx) ?? self.headerHeight
if heightHeader > 0 {
let attributes = CollectionViewLayoutAttributes(forSupplementaryViewOfKind: CollectionViewLayoutElementKind.SectionHeader,
with: IndexPath.for(section: sectionIdx))
attributes.frame = insetSupplementaryViews
? CGRect(x: sectionInsets.left, y: top, width: contentWidth, height: heightHeader).integral
: CGRect(x: contentInsets.left, y: top, width: cv.frame.size.width - contentInsets.width, height: heightHeader).integral
section.header = attributes
top = attributes.frame.maxY
}
top += sectionInsets.top
section.prepareColumns(colCount,
spacing: columnSpacing,
in: CGRect(x: sectionInsets.left, y: top, width: contentWidth, height: 0))
// 3. Section items
let itemCount = cv.numberOfItems(in: sectionIdx)
// Item will be put into shortest column.
for idx in 0..<itemCount {
let indexPath = IndexPath.for(item: idx, section: sectionIdx)
allIndexPaths.append(indexPath)
let ratio = self.delegate?.collectionView?(cv, layout: self, aspectRatioForItemAt: indexPath)
let height = self.delegate?.collectionView?(cv, layout: self, heightForItemAt: indexPath)
section.addItem(for: indexPath,
aspectRatio: ratio,
variableHeight: height,
defaultHeight: self.itemHeight,
spacing: itemSpacing, strategy: self.layoutStrategy)
}
// 4. Section footer
section.finalizeColumns()
top = section.frame.maxY
let footerHeight = self.delegate?.collectionView?(cv, layout: self, heightForFooterInSection: sectionIdx) ?? self.footerHeight
if footerHeight > 0 {
let attributes = CollectionViewLayoutAttributes(forSupplementaryViewOfKind: CollectionViewLayoutElementKind.SectionFooter,
with: IndexPath.for(item: 0, section: sectionIdx))
attributes.frame = insetSupplementaryViews ?
CGRect(x: sectionInsets.left, y: top, width: cv.contentVisibleRect.size.width - sectionInsets.width, height: footerHeight)
: CGRect(x: 0, y: top, width: cv.contentVisibleRect.size.width, height: footerHeight)
section.footer = attributes
section.frame.size.height += attributes.frame.size.height
top = attributes.frame.maxY
}
section.frame.size.height += sectionInsets.bottom
top = section.frame.maxY
sections.append(section)
}
}
override open var collectionViewContentSize: CGSize {
guard let cv = collectionView else { return CGSize.zero }
var contentSize = cv.contentVisibleRect.size
contentSize.width -= cv.contentInsets.width
let height = self.sections.last?.frame.maxY ?? 0
contentSize.height = height
return contentSize
}
open override func rectForSection(_ section: Int) -> CGRect {
return self.sections[section].frame
}
open override func contentRectForSection(_ section: Int) -> CGRect {
return self.sections[section].contentFrame
}
open override func indexPathsForItems(in rect: CGRect) -> [IndexPath] {
return itemAttributes(in: rect) { return $0.indexPath }
}
open override func layoutAttributesForItems(in rect: CGRect) -> [CollectionViewLayoutAttributes] {
return itemAttributes(in: rect) { return $0.copy() }
}
open func itemAttributes<T>(in rect: CGRect, reducer: ((CollectionViewLayoutAttributes) -> T)) -> [T] {
guard !rect.isEmpty && !self.sections.isEmpty else { return [] }
var results = [T]()
for section in self.sections {
// If we have passed the target, finish
guard !section.items.isEmpty && section.frame.intersects(rect) else {
guard section.frame.origin.y < rect.maxY else { break }
continue
}
if rect.contains(section.contentFrame) {
results.append(contentsOf: section.items.map { return reducer($0) })
} else {
for column in section.columns {
guard column.frame.intersects(rect) else {
continue
}
for item in column.items {
guard item.frame.intersects(rect) else {
continue
}
results.append(reducer(item))
}
}
}
}
return results
}
open override func layoutAttributesForItem(at indexPath: IndexPath) -> CollectionViewLayoutAttributes? {
return self.sections.object(at: indexPath._section)?.items.object(at: indexPath._item)?.copy()
}
open override func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> CollectionViewLayoutAttributes? {
let section = self.sections[indexPath._section]
if elementKind == CollectionViewLayoutElementKind.SectionHeader {
guard let attrs = section.header?.copy() else { return nil }
if pinHeadersToTop, let cv = self.collectionView {
let contentOffset = cv.contentOffset
let frame = attrs.frame
var nextHeaderOrigin = CGPoint(x: CGFloat.greatestFiniteMagnitude, y: CGFloat.greatestFiniteMagnitude)
if let nextHeader = self.sections.object(at: indexPath._section + 1)?.header {
nextHeaderOrigin = nextHeader.frame.origin
}
let topInset = cv.contentInsets.top
attrs.frame.origin.y = min(max(contentOffset.y + topInset, frame.origin.y), nextHeaderOrigin.y - frame.height)
attrs.floating = indexPath._section == 0 || attrs.frame.origin.y > frame.origin.y
}
return attrs
} else if elementKind == CollectionViewLayoutElementKind.SectionFooter {
return section.footer?.copy()
}
return nil
}
open override func scrollRectForItem(at indexPath: IndexPath, atPosition: CollectionViewScrollPosition) -> CGRect? {
guard var frame = self.layoutAttributesForItem(at: indexPath)?.frame else { return nil }
let inset = (self.collectionView?.contentInsets.top ?? 0)
if self.pinHeadersToTop,
let attrs = self.layoutAttributesForSupplementaryView(ofKind: CollectionViewLayoutElementKind.SectionHeader,
at: IndexPath.for(item: 0, section: indexPath._section)) {
let y = (frame.origin.y - attrs.frame.size.height) // + inset
let height = frame.size.height + attrs.frame.size.height
frame.size.height = height
frame.origin.y = y
} else {
frame.origin.y += inset
}
return frame
}
open override func indexPathForNextItem(moving direction: CollectionViewDirection, from currentIndexPath: IndexPath) -> IndexPath? {
guard let collectionView = self.collectionView else { fatalError() }
var index = currentIndexPath._item
var section = currentIndexPath._section
let numberOfSections = collectionView.numberOfSections
let numberOfItemsInSection = collectionView.numberOfItems(in: currentIndexPath._section)
guard collectionView.rectForItem(at: currentIndexPath) != nil else { return nil }
switch direction {
case .up:
guard let cAttrs = collectionView.layoutAttributesForItem(at: currentIndexPath),
let columns = self.sections.object(at: section)?.columns else { return nil }
let cFlat = CGRect(x: cAttrs.frame.origin.x, y: 0, width: cAttrs.frame.size.width, height: 50)
for column in columns {
if let first = column.items.first {
// This is the first item in the column -> Check the previous section
if first.indexPath == currentIndexPath {
guard let previousSection = sections.object(at: section - 1) else { return nil }
let pColumns = previousSection.columns
for col in pColumns.reversed() where !col.items.isEmpty {
let flat = CGRect(x: col.frame.origin.x, y: 0, width: col.frame.size.width, height: 50)
if cFlat.intersects(flat) {
return col.items.last?.indexPath
}
}
return previousSection.items.last?.indexPath
}
let flat = CGRect(x: first.frame.origin.x, y: 0, width: first.frame.size.width, height: 50)
// Get the same column
if cFlat.intersects(flat) {
guard let idx = (column.items.firstIndex { return $0.indexPath == currentIndexPath }) else {
return nil
}
let next = column.items.index(before: idx)
return column.items.object(at: next)?.indexPath
}
}
}
return nil
case .down:
guard let cAttrs = collectionView.layoutAttributesForItem(at: currentIndexPath),
let columns = self.sections.object(at: section)?.columns else { return nil }
let cFlat = CGRect(x: cAttrs.frame.origin.x, y: 0, width: cAttrs.frame.size.width, height: 50)
for column in columns {
if let first = column.items.first {
// This is the last item in the column -> Check the previous section
if column.items.last?.indexPath == currentIndexPath {
guard let nextSection = sections.object(at: section + 1) else { return nil }
let pColumns = nextSection.columns
for col in pColumns where !col.items.isEmpty {
let flat = CGRect(x: col.frame.origin.x, y: 0, width: col.frame.size.width, height: 50)
if cFlat.intersects(flat) {
return col.items.first?.indexPath
}
}
return nextSection.items.last?.indexPath
}
let flat = CGRect(x: first.frame.origin.x, y: 0, width: first.frame.size.width, height: 50)
// Get the same column
if cFlat.intersects(flat) {
guard let idx = (column.items.firstIndex { return $0.indexPath == currentIndexPath }) else {
return nil
}
let next = column.items.index(after: idx)
return column.items.object(at: next)?.indexPath
}
}
}
return nil
case .left:
if section == 0 && index == 0 {
return currentIndexPath
}
if index > 0 {
index -= 1
} else {
section -= 1
index = collectionView.numberOfItems(in: currentIndexPath._section - 1) - 1
}
return IndexPath.for(item: index, section: section)
case .right :
if section == numberOfSections - 1 && index == numberOfItemsInSection - 1 {
return currentIndexPath
}
if index < numberOfItemsInSection - 1 {
index += 1
} else {
section += 1
index = 0
}
return IndexPath.for(item: index, section: section)
}
}
}
| 04b0c5ed5e49a701690d25f40dc810de | 45.483278 | 420 | 0.587078 | false | false | false | false |
tianyc1019/LSPhotoPicker | refs/heads/master | LSPhotoPicker/LSPhotoPicker/LSPhotoPicker/LSPhotoShow/LSSinglePhotoPreviewViewController.swift | mit | 1 | //
// LSSinglePhotoPreviewViewController.swift
// LSPhotoPicker
//
// Created by John_LS on 2017/2/9.
// Copyright © 2017年 John_LS. All rights reserved.
//
import UIKit
class LSSinglePhotoPreviewViewController: UIViewController {
var selectImages:[LSPhotosModel]?
var collectionView: UICollectionView?
let cellIdentifier = "cellIdentifier"
var currentPage: Int = 0
weak var sourceDelegate: LSPhotosView?
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.navigationItem.backBarButtonItem = UIBarButtonItem.init(title: "back", style: .plain, target: self, action: nil)
self.ls_configNavigationBar()
self.ls_configCollectionView()
}
private func ls_configNavigationBar(){
self.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: self, action: #selector(LSSinglePhotoPreviewViewController.ls_eventGoBack))
UIApplication.shared.statusBarStyle = .lightContent
self.navigationController?.navigationBar.barStyle = .black
self.navigationController?.navigationBar.tintColor = UIColor.white
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .trash, target: self, action: #selector(LSSinglePhotoPreviewViewController.ls_eventRemoveImage))
}
/// 删除按钮
func ls_eventRemoveImage(){
let element = self.selectImages?.remove(at: self.currentPage)
self.ls_updatePageTitle()
self.sourceDelegate?.ls_removeElement(element: element)
if (self.selectImages?.count)! > 0{
self.collectionView?.reloadData()
} else {
self.navigationController?.dismiss(animated: true, completion: nil)
}
}
/// 返回
func ls_eventGoBack(){
self.navigationController?.dismiss(animated: true, completion: {
})
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.collectionView?.setContentOffset(CGPoint(x: CGFloat(self.currentPage) * self.view.bounds.width, y: 0), animated: false)
self.ls_updatePageTitle()
}
func ls_updatePageTitle(){
self.title = String(self.currentPage+1) + "/" + String(self.selectImages!.count)
}
}
extension LSSinglePhotoPreviewViewController : UICollectionViewDataSource,UICollectionViewDelegate{
func ls_configCollectionView(){
self.automaticallyAdjustsScrollViewInsets = false
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .horizontal
layout.itemSize = CGSize(width:self.view.frame.width,height: self.view.frame.height)
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
self.collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
self.collectionView!.dataSource = self
self.collectionView!.delegate = self
self.collectionView!.isPagingEnabled = true
self.collectionView!.scrollsToTop = false
self.collectionView!.showsHorizontalScrollIndicator = false
self.collectionView!.contentOffset = CGPoint(x:0, y: 0)
self.collectionView!.contentSize = CGSize(width: self.view.bounds.width * CGFloat(self.selectImages!.count), height: self.view.bounds.height)
self.view.addSubview(self.collectionView!)
self.collectionView!.register(LSPhotoPreviewCell.self, forCellWithReuseIdentifier: self.cellIdentifier)
}
// MARK: - collectionView dataSource delagate
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.selectImages!.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: self.cellIdentifier, for: indexPath) as! LSPhotoPreviewCell
cell.delegate = self
if let asset = self.selectImages?[indexPath.row] {
cell.ls_renderModel(asset: asset.data,img:asset.img)
}
return cell
}
// MARK: - scroll page
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offset = scrollView.contentOffset
self.currentPage = Int(offset.x / self.view.bounds.width)
self.ls_updatePageTitle()
}
}
extension LSSinglePhotoPreviewViewController : LSPhotoPreviewCellDelegate{
// MARK: - Photo Preview Cell Delegate
func ls_onImageSingleTap() {
let status = !(self.navigationController?.isNavigationBarHidden)!
self.navigationController?.setNavigationBarHidden(status, animated: true)
}
}
| 1a216c7500838f19825ccb64d353dfe3 | 37.109375 | 182 | 0.687987 | false | false | false | false |
flovouin/AsyncDisplayKit | refs/heads/master | examples_extra/ASDKgram-Swift/ASDKgram-Swift/Webservice.swift | bsd-3-clause | 5 | //
// Webservice.swift
// ASDKgram-Swift
//
// Created by Calum Harris on 06/01/2017.
//
// Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// swiftlint:disable force_cast
import UIKit
final class WebService {
func load<A>(resource: Resource<A>, completion: @escaping (Result<A>) -> ()) {
URLSession.shared.dataTask(with: resource.url) { data, response, error in
// Check for errors in responses.
let result = self.checkForNetworkErrors(data, response, error)
switch result {
case .success(let data):
completion(resource.parse(data))
case .failure(let error):
completion(.failure(error))
}
}.resume()
}
}
extension WebService {
fileprivate func checkForNetworkErrors(_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Result<Data> {
// Check for errors in responses.
guard error == nil else {
if (error as! NSError).domain == NSURLErrorDomain && ((error as! NSError).code == NSURLErrorNotConnectedToInternet || (error as! NSError).code == NSURLErrorTimedOut) {
return .failure(.noInternetConnection)
} else {
return .failure(.returnedError(error!))
}
}
guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
return .failure((.invalidStatusCode("Request returned status code other than 2xx \(response)")))
}
guard let data = data else { return .failure(.dataReturnedNil) }
return .success(data)
}
}
struct Resource<A> {
let url: URL
let parse: (Data) -> Result<A>
}
extension Resource {
init(url: URL, parseJSON: @escaping (Any) -> Result<A>) {
self.url = url
self.parse = { data in
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: [])
return parseJSON(jsonData)
} catch {
fatalError("Error parsing data")
}
}
}
}
enum Result<T> {
case success(T)
case failure(NetworkingErrors)
}
enum NetworkingErrors: Error {
case errorParsingJSON
case noInternetConnection
case dataReturnedNil
case returnedError(Error)
case invalidStatusCode(String)
case customError(String)
}
| aea84d3e09c5ca1bd561dfb633b27e92 | 29.182796 | 170 | 0.706092 | false | false | false | false |
jaouahbi/OMCircularProgress | refs/heads/master | OMCircularProgress/Classes/Extensions/UIFont+Extensions.swift | apache-2.0 | 2 | //
// UIFont+Extensions.swift
//
// Created by Jorge Ouahbi on 17/11/16.
// Copyright © 2016 Jorge Ouahbi. All rights reserved.
//
import UIKit
extension UIFont {
func stringSize(s:String,size:CGSize) -> CGSize {
for i in (4...32).reversed() {
let d = [NSAttributedString.Key.font:UIFont(name:fontName, size:CGFloat(i))!]
let sz = (s as NSString).size(withAttributes: d)
if sz.width <= size.width && sz.height <= size.height {
return sz
}
}
return CGSize.zero
}
static func stringSize(s:String,fontName:String,size:CGSize) -> CGSize {
for i in (4...32).reversed() {
let d = [NSAttributedString.Key.font:UIFont(name:fontName, size:CGFloat(i))!]
let sz = (s as NSString).size(withAttributes: d)
if sz.width <= size.width && sz.height <= size.height {
return sz
}
}
return CGSize.zero
}
}
| 0522664198b8a87342948c3aeca43c53 | 28.969697 | 89 | 0.55814 | false | false | false | false |
lennet/proNotes | refs/heads/master | app/proNotes/DocumentOverview/WelcomeViewController.swift | mit | 1 | //
// WelcomeViewController.swift
// proNotes
//
// Created by Leo Thomas on 27/04/16.
// Copyright © 2016 leonardthomas. All rights reserved.
//
import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet weak var backLeftXConstraint: NSLayoutConstraint!
@IBOutlet weak var backRightXConstraint: NSLayoutConstraint!
@IBOutlet weak var middleLeftXConstraint: NSLayoutConstraint!
@IBOutlet weak var middleRightXConstraint: NSLayoutConstraint!
@IBOutlet weak var topImageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
for case let imageView as UIImageView in view.subviews {
imageView.layer.setUpDefaultShaddow()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
Preferences.isFirstRun = false
animateImageViews()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
func animateImageViews() {
view.layoutIfNeeded()
let middleOffSet: CGFloat = topImageView.bounds.width/3.8
middleLeftXConstraint.constant = -middleOffSet
middleRightXConstraint.constant = middleOffSet
let backOffset: CGFloat = topImageView.bounds.width/2.1
backLeftXConstraint.constant = -backOffset
backRightXConstraint.constant = backOffset
UIView.animate(withDuration: 1, delay: 0.2, options: UIViewAnimationOptions(), animations: {
self.view.layoutIfNeeded()
}, completion: nil)
}
@IBAction func handleContinueButtonPressed(_ sender: AnyObject) {
Preferences.showWelcomeScreen = false
presentingViewController?.dismiss(animated: true, completion: nil)
}
}
| 29fb8dbcc445a35d70f6d0146c303c69 | 31.6 | 100 | 0.692694 | false | false | false | false |
grpc/grpc-swift | refs/heads/main | Sources/GRPC/GRPCTimeout.swift | apache-2.0 | 1 | /*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Dispatch
import NIOCore
/// A timeout for a gRPC call.
///
/// Timeouts must be positive and at most 8-digits long.
public struct GRPCTimeout: CustomStringConvertible, Equatable {
/// Creates an infinite timeout. This is a sentinel value which must __not__ be sent to a gRPC service.
public static let infinite = GRPCTimeout(
nanoseconds: Int64.max,
wireEncoding: "infinite"
)
/// The largest amount of any unit of time which may be represented by a gRPC timeout.
internal static let maxAmount: Int64 = 99_999_999
/// The wire encoding of this timeout as described in the gRPC protocol.
/// See: https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md.
public let wireEncoding: String
public let nanoseconds: Int64
public var description: String {
return self.wireEncoding
}
/// Creates a timeout from the given deadline.
///
/// - Parameter deadline: The deadline to create a timeout from.
internal init(deadline: NIODeadline, testingOnlyNow: NIODeadline? = nil) {
switch deadline {
case .distantFuture:
self = .infinite
default:
let timeAmountUntilDeadline = deadline - (testingOnlyNow ?? .now())
self.init(rounding: timeAmountUntilDeadline.nanoseconds, unit: .nanoseconds)
}
}
private init(nanoseconds: Int64, wireEncoding: String) {
self.nanoseconds = nanoseconds
self.wireEncoding = wireEncoding
}
/// Creates a `GRPCTimeout`.
///
/// - Precondition: The amount should be greater than or equal to zero and less than or equal
/// to `GRPCTimeout.maxAmount`.
internal init(amount: Int64, unit: GRPCTimeoutUnit) {
precondition(amount >= 0 && amount <= GRPCTimeout.maxAmount)
// See "Timeout" in https://github.com/grpc/grpc/blob/master/doc/PROTOCOL-HTTP2.md#requests
// If we overflow at this point, which is certainly possible if `amount` is sufficiently large
// and `unit` is `.hours`, clamp the nanosecond timeout to `Int64.max`. It's about 292 years so
// it should be long enough for the user not to notice the difference should the rpc time out.
let (partial, overflow) = amount.multipliedReportingOverflow(by: unit.asNanoseconds)
self.init(
nanoseconds: overflow ? Int64.max : partial,
wireEncoding: "\(amount)\(unit.rawValue)"
)
}
/// Create a timeout by rounding up the timeout so that it may be represented in the gRPC
/// wire format.
internal init(rounding amount: Int64, unit: GRPCTimeoutUnit) {
var roundedAmount = amount
var roundedUnit = unit
if roundedAmount <= 0 {
roundedAmount = 0
} else {
while roundedAmount > GRPCTimeout.maxAmount {
switch roundedUnit {
case .nanoseconds:
roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 1000)
roundedUnit = .microseconds
case .microseconds:
roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 1000)
roundedUnit = .milliseconds
case .milliseconds:
roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 1000)
roundedUnit = .seconds
case .seconds:
roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 60)
roundedUnit = .minutes
case .minutes:
roundedAmount = roundedAmount.quotientRoundedUp(dividingBy: 60)
roundedUnit = .hours
case .hours:
roundedAmount = GRPCTimeout.maxAmount
roundedUnit = .hours
}
}
}
self.init(amount: roundedAmount, unit: roundedUnit)
}
}
extension Int64 {
/// Returns the quotient of this value when divided by `divisor` rounded up to the nearest
/// multiple of `divisor` if the remainder is non-zero.
///
/// - Parameter divisor: The value to divide this value by.
fileprivate func quotientRoundedUp(dividingBy divisor: Int64) -> Int64 {
let (quotient, remainder) = self.quotientAndRemainder(dividingBy: divisor)
return quotient + (remainder != 0 ? 1 : 0)
}
}
internal enum GRPCTimeoutUnit: String {
case hours = "H"
case minutes = "M"
case seconds = "S"
case milliseconds = "m"
case microseconds = "u"
case nanoseconds = "n"
internal var asNanoseconds: Int64 {
switch self {
case .hours:
return 60 * 60 * 1000 * 1000 * 1000
case .minutes:
return 60 * 1000 * 1000 * 1000
case .seconds:
return 1000 * 1000 * 1000
case .milliseconds:
return 1000 * 1000
case .microseconds:
return 1000
case .nanoseconds:
return 1
}
}
}
| af807670f4351bb937043bd8950d22f6 | 32.36129 | 105 | 0.684587 | false | false | false | false |
kgn/KGNSpriteKit | refs/heads/master | Source/ShaderView.swift | mit | 1 | //
// ShaderView.swift
// KGNSpriteKit
//
// Created by David Keegan on 6/3/16.
// Copyright © 2016 David Keegan. All rights reserved.
//
import SpriteKit
fileprivate extension Selector {
static let updateSize = #selector(ShaderView.updateSize)
}
open class ShaderView: SKView {
#if os(OSX)
let screenScale = NSScreen.mainScreen()!.backingScaleFactor
public var backgroundColor: NSColor? {
get {
return self.scene?.backgroundColor
}
set {
let color = newValue ?? .clearColor()
self.scene?.backgroundColor = color
self.allowsTransparency = CGColorGetAlpha(color.CGColor) < 1
}
}
#else
let screenScale = UIScreen.main.scale
override open var backgroundColor: UIColor? {
get {
return self.scene?.backgroundColor
}
set {
let color = newValue ?? .clear
self.scene?.backgroundColor = color
self.allowsTransparency = color.cgColor.alpha < 1
}
}
#endif
open var shouldRasterize: Bool {
get {
return self.rasterNode.shouldRasterize
}
set {
if self.rasterNode.shouldRasterize != newValue {
self.rasterNode.shouldRasterize = newValue
}
}
}
open var shader: SKShader? {
didSet {
if self.shader == oldValue {
return
}
self.shader?.addUniform(self.spriteScale)
self.shader?.addUniform(self.spritePixelSize)
self.shader?.addUniform(self.spriteSize)
self.shader?.addUniform(self.spriteAspectRatio)
self.shaderNode.shader = self.shader
}
}
private var privateLastSize: CGSize?
open var lastSize: CGSize? {
return self.privateLastSize
}
private lazy var spriteScale = SKUniform(name: "c_sprite_scale", float: 0)
private lazy var spritePixelSize = SKUniform(name: "c_sprite_pixel_size", float: 0)
private lazy var spriteSize = SKUniform(name: "c_sprite_size", float2: (0, 0))
private lazy var spriteAspectRatio = SKUniform(name: "c_sprite_aspect_ratio", float2: (0, 0))
private lazy var rasterNode = SKEffectNode()
private lazy var shaderNode: SKSpriteNode = {
let node = SKSpriteNode()
node.anchorPoint = CGPoint.zero
return node
}()
#if os(OSX)
override public init(frame frameRect: NSRect) {
super.init(frame: frameRect)
self.setup()
}
#else
override public init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
open override func layoutSubviews() {
super.layoutSubviews()
self.updateSize()
}
#endif
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
open func setup() {
let scene = SKScene()
scene.addChild(self.rasterNode)
self.rasterNode.addChild(self.shaderNode)
self.presentScene(scene)
#if os(OSX)
self.postsBoundsChangedNotifications = true
NSNotificationCenter.defaultCenter().addObserver(self, selector: .updateSize, name: nil, object: nil)
#endif
}
@objc fileprivate func updateSize() {
if self.bounds.isEmpty {
return
}
if self.bounds.size == self.lastSize {
return
}
let x = Float(self.bounds.size.width)
let y = Float(self.bounds.size.height)
self.spriteSize.float2 = (x, y)
let aspectX: Float = x > y ? x/y : 1
let aspectY: Float = x < y ? y/x : 1
self.spriteAspectRatio.float2 = (aspectX, aspectY)
let scale = UIScreen.main.scale
self.spriteScale.floatValue = Float(scale)
self.spritePixelSize.floatValue = Float(1/min(x, y))
self.scene?.size = self.bounds.size
self.shaderNode.size = self.bounds.size
}
}
| 4ae0fa694a4f41fb9de482b9f15b8a0a | 26.417219 | 109 | 0.578019 | false | false | false | false |
GeoThings/LakestoneCore | refs/heads/master | Source/LakestoneError.swift | apache-2.0 | 1 | //
// ErrorType.swift
// LakestoneCore
//
// Created by Taras Vozniuk on 9/20/16.
// Copyright © 2016 GeoThings. All rights reserved.
//
// --------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Throwable Error abstractions and its related types
//
//MARK: - ErrorRepresentable
/// A type that can be carried inside `LakestoneError`
///
/// Any type that conforms to `ErrorRepresentable` can be used as
/// the carried entity that identifiers the LakestoneError instance being thrown
///
/// - note: `detailMessage` is the string representation (error description) of `ErrorRepresentable` entity,
/// which is required for Java runtime thrown exceptions
/// - warning: avoid using conventional swift way of having error backed by `enum` type
/// if you building with Silver for Java, since at this moment (8.4.96.2041)
/// silver enums are extremely unstable
public protocol ErrorRepresentable: CustomStringConvertible {
var detailMessage: String { get }
}
extension String: ErrorRepresentable {
public var description: String {
return self
}
public var detailMessage: String {
return self.description
}
}
extension ErrorRepresentable {
public var description: String {
return self.detailMessage
}
}
public func ==(lhs: ErrorRepresentable, rhs: ErrorRepresentable) -> Bool {
return lhs.detailMessage == rhs.detailMessage
}
//MARK: - StringBackedErrorType
/// Error representable type that is backed by string entity
///
/// This is the most default container to represent simple error types
///
/// //instaniate a simple string-backed error
/// LakestoneError(StringBackedErrorType("Request is missing"))
///
open class StringBackedErrorType: ErrorRepresentable {
public let representation: String
public init(_ representation: String) { self.representation = representation }
public var detailMessage: String { return self.representation }
}
#if COOPER
extension StringBackedErrorType {
public override func toString() -> String {
return self.description
}
}
#endif
//MARK: - LakestoneError
#if !COOPER
/// Throwable error container
///
/// This boxed type represent the actual error object being thrown.
/// Error entity is identified with enclosed error representation.
/// Any custom type that provides its error description as required by `ErrorRepresentable`
/// protocol can be carried inside this boxed error type.
///
/// In Java this is a concrete subclass of `java.lang.Exception`,
/// the `detailMessage` of `ErrorRepresentable` is actually used as a carried exception message
/// of its superclass `java.lang.Throwable`
///
/// The recommended usage involves storing the instances of it as static variables under the
/// gathering member class type
///
/// //sample class
/// public class Request {
///
/// //error reassambles embedded gathering class type
/// public class Error {
/// static let ResponseMissing = LakestoneError.with(stringRepresentation: "Response is missing")
/// static let DestinationUnreachable = LakestoneError.with(stringRepresentation: "Destination is unreachable")
/// }
/// }
///
/// Within the class the error can then be thrown in a natural way:
///
/// throw Error.DestinationUnreachable
///
/// And handled as following:
///
/// do {
/// let response = try HTTP("http://wrongdestination.com").performSync()
/// } catch let error as LakestoneError {
/// print("Error encountered: \(error.representation)")
/// }
///
/// In Apple's swift catch clause can also be written more specifically:
///
/// catch let error as LakestoneError where error == HTTP.Request.Error.ResponseMissing
///
/// - remark: Despite the conventional way of backing swift errors with enums,
/// for sake of consistency with Java, it is implemented as class type
open class LakestoneError: Error {
public let representation: ErrorRepresentable
public init(_ representation: ErrorRepresentable){
self.representation = representation
}
}
#else
open class LakestoneError: java.lang.Exception {
public let representation: ErrorRepresentable
public init(_ representation: ErrorRepresentable){
super.init(representation.detailMessage)
self.representation = representation
}
}
#endif
extension LakestoneError {
open class func with(stringRepresentation: String) -> LakestoneError {
return LakestoneError(StringBackedErrorType(stringRepresentation))
}
#if COOPER
open class func withStringRepresentation(_ string: String) -> LakestoneError {
return self.with(stringRepresentation: string)
}
#endif
}
extension LakestoneError: CustomStringConvertible {
public var description: String {
return self.representation.detailMessage
}
#if COOPER
public override func toString() -> String {
return self.description
}
#endif
}
extension LakestoneError: Equatable {}
public func ==(lhs: LakestoneError, rhs: LakestoneError) -> Bool {
return lhs.representation == rhs.representation
}
#if COOPER
extension LakestoneError {
public override func equals(_ o: Object!) -> Bool {
guard let other = o as? Self else {
return false
}
return (self == other)
}
}
#endif
// Silver will catch the error as being of Object type, while in asynchronous callbacks
// you want to return the error straight away as entity of ThrowableError type
// this is a convenience func for such purpose
#if COOPER
public func castedError(_ entity: Any) -> ThrowableError? {
return entity as? ThrowableError
}
#else
public func castedError(_ entity: ThrowableError) -> ThrowableError? {
return entity
}
#endif
public class DictionaryInstantiationError: LakestoneError {
var instantiationRepresentationº: Representation? {
return self.representation as? Representation
}
public class Representation: ErrorRepresentable {
public let fieldName: String
public let detail: String
public init(fieldName: String, detail: String){
self.fieldName = fieldName
self.detail = detail
}
public var detailMessage: String {
return "Entity couldn't be instantiated: error in field: \(fieldName): \(self.detail)"
}
public var error: DictionaryInstantiationError {
return DictionaryInstantiationError(self)
}
}
public static func defaultDetail(forType type: AnyType) -> String {
return "Field is missing or has non \(type) type"
}
}
| 974787b96d4f519ed529699fed68c41a | 27.47541 | 123 | 0.725533 | false | false | false | false |
Ribeiro/SwiftStructures | refs/heads/master | Source/Factories/Queue.swift | mit | 4 | //
// Queue.swift
// SwiftStructures
//
// Created by Wayne Bishop on 7/11/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
public class Queue<T> {
private var top: QNode<T>! = QNode<T>()
//the number of items
var count: Int {
if (top.key == nil) {
return 0
}
else {
var current: QNode<T> = top
var x: Int = 1
//cycle through the list of items
while (current.next != nil) {
current = current.next!;
x++
}
return x
}
}
//enqueue the specified object
func enQueue(key: T) {
//check for the instance
if (top == nil) {
top = QNode<T>()
}
//establish the top node
if (top.key == nil) {
top.key = key;
return
}
var childToUse: QNode<T> = QNode<T>()
var current: QNode = top
//cycle through the list of items to get to the end.
while (current.next != nil) {
current = current.next!
}
//append a new item
childToUse.key = key;
current.next = childToUse;
}
//retrieve the top most item
func peek() -> T? {
return top.key!
}
//retrieve items from the top level in O(1) constant time
func deQueue() -> T? {
//determine if the key or instance exist
let topitem: T? = self.top?.key
if (topitem == nil) {
return nil
}
//retrieve and queue the next item
var queueitem: T? = top.key!
//use optional binding
if let nextitem = top.next {
top = nextitem
}
else {
top = nil
}
return queueitem
}
//check for the presence of a value
func isEmpty() -> Bool {
//determine if the key or instance exist
if let topitem: T = self.top?.key {
return false
}
else {
return true
}
}
} //end class
| 0f0df4ef05d8ed6301419835b90cb50d | 17.18797 | 65 | 0.421662 | false | false | false | false |
willowtreeapps/go-timestamp-example | refs/heads/master | ios/Timestamps/ViewController.swift | mit | 1 | //
// ViewController.swift
// Timestamps
//
// Created by Ian Terrell on 10/9/15.
// Copyright © 2015 WillowTree Apps. All rights reserved.
//
import UIKit
import Timestamp
struct TS: CustomStringConvertible {
static var Formatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = NSDateFormatterStyle.LongStyle
formatter.timeStyle = .MediumStyle
return formatter
}()
let time: NSDate
init(json: NSDictionary) {
let s = json["seconds_since_epoch"] as! NSNumber
time = NSDate(timeIntervalSince1970: s.doubleValue)
}
static func parse(jsonData: NSData) throws -> [TS] {
let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: .AllowFragments) as! NSArray
var timestamps = [TS]()
for case let dict as NSDictionary in json {
timestamps.append(TS(json: dict))
}
return timestamps
}
var description: String {
return TS.Formatter.stringFromDate(time)
}
}
class ViewController: UITableViewController {
var timestamps = [TS]()
override func viewDidLoad() {
super.viewDidLoad()
reloadTimestamps()
}
func reloadTimestamps() {
var data: NSData?
var error: NSError?
Timestamp.GoTimestampAllJSON(&data, &error)
guard error == nil else {
print("Error getting timestamps: \(error)")
return
}
do {
timestamps = try TS.parse(data!)
} catch {
print("Error parsing timestamps: \(error)")
}
tableView.reloadData()
}
@IBAction func addTimestamp(sender: AnyObject) {
var error: NSError?
let now = NSDate().timeIntervalSince1970
Timestamp.GoTimestampInsert(Int64(now), &error)
guard error == nil else {
print("Error inserting timestamp: \(error)")
return
}
reloadTimestamps()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return timestamps.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TimestampCell")!
cell.textLabel?.text = timestamps[indexPath.row].description
return cell
}
}
| 67929eb685043dd1b08a48a10e2ad43a | 26.442105 | 118 | 0.613349 | false | false | false | false |
tutsplus/iOS-GameplayKit-StarterProject | refs/heads/master | GameplayKit Introduction/PlayerNode.swift | bsd-2-clause | 1 | //
// PlayerNode.swift
// GameplayKit Introduction
//
// Created by Davis Allie on 19/07/2015.
// Copyright © 2015 Davis Allie. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class PlayerNode: SKShapeNode {
var enabled = true {
didSet {
if self.enabled == false {
self.alpha = 0.1
self.runAction(SKAction.customActionWithDuration(2.0, actionBlock: { (node, elapsedTime) -> Void in
if elapsedTime == 2.0 {
self.enabled = true
}
}))
self.runAction(SKAction.fadeInWithDuration(2.0))
}
}
}
}
| 906b7cdddaef51fe6d700e63b2d4daf7 | 23.5 | 115 | 0.510204 | false | false | false | false |
daaavid/TIY-Assignments | refs/heads/master | 44--Philosophone/Philosophone/Philosophone/APIController.swift | cc0-1.0 | 1 | //
// APIController.swift
// Philosophone
//
// Created by david on 12/4/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import Foundation
class APIController
{
var delegate: APIControllerProtocol?
init(delegate: APIControllerProtocol)
{
self.delegate = delegate
}
func getQuote(categories: [String])
{
let baseURL = "http://api.theysaidso.com/qod.json?category="
var category = ""
if categories.count > 1
{
let randomIndex = Int(arc4random() % UInt32(categories.count - 1))
category = categories[randomIndex]
}
if let url = NSURL(string: (baseURL + category))
{
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url, completionHandler: { (data, _, error) -> Void in
if data != nil
{
if let dictionary = self.parseJSON(data!)
{
print(self.delegate)
self.delegate?.quoteWasFound(dictionary)
}
}
else
{
print(error?.localizedDescription)
self.delegate?.quoteWasFound(nil)
}
}).resume()
}
else
{
print("invalid url: \(baseURL + category)")
}
}
func parseJSON(data: NSData) -> NSDictionary?
{
do
{
let dictionary: NSDictionary! = try NSJSONSerialization.JSONObjectWithData(data, options: []) as! NSDictionary
print("parsed JSON")
return dictionary
}
catch let error as NSError
{
print(error)
return nil
}
}
} | 60952bd40faf9aced7fd9b9f4c6cdc4c | 24.506667 | 122 | 0.476464 | false | false | false | false |
CD1212/Doughnut | refs/heads/master | Pods/FeedKit/Sources/FeedKit/Dates/ISO8601DateFormatter.swift | gpl-3.0 | 2 | //
// ISO8601DateFormatter.swift
//
// Copyright (c) 2017 Nuno Manuel Dias
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/// Converts date and time textual representations within the ISO8601
/// date specification into `Date` objects
class ISO8601DateFormatter: DateFormatter {
let dateFormats = [
"yyyy-mm-dd'T'hh:mm",
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ",
"yyyy-MM-dd'T'HH:mmSSZZZZZ"
]
override init() {
super.init()
self.timeZone = TimeZone(secondsFromGMT: 0)
self.locale = Locale(identifier: "en_US_POSIX")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func date(from string: String) -> Date? {
for dateFormat in self.dateFormats {
self.dateFormat = dateFormat
if let date = super.date(from: string) {
return date
}
}
return nil
}
}
| 25dee231f5ac6ca3bac4b3783468b041 | 34.896552 | 82 | 0.673391 | false | false | false | false |
kevin0511/MyCM | refs/heads/master | cm/cm/ShootViewController.swift | mit | 1 | //
// ShootViewController.swift
// CM
//
// Created by Kevin on 2017/5/16.
// Copyright © 2017年 Kevin. All rights reserved.
//
import UIKit
class ShootViewController: UIViewController {
var vm = ShootViewModel()
var model = ShootModel()
let selfBounds = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: kScreenW, height:kScreenH - (kStateBarH + kNavgationBarH + kMainTitleViewH + kTabBarH)))
fileprivate lazy var tableView: UITableView = {[weak self] in
let tv = UITableView.init(frame:(self?.selfBounds)!)
tv.delegate = self?.vm
tv.dataSource = self?.vm
tv.separatorStyle = UITableViewCellSeparatorStyle.none
tv.bounces = false
return tv
}()
override func viewDidLoad() {
super.viewDidLoad()
self.vm.model = self.model
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ShootViewController {
fileprivate func setupUI(){
self.view.bounds = self.selfBounds
view.addSubview(tableView)
}
}
| 1c15e076f67d666e1abd9770aa97d74a | 21.821429 | 169 | 0.596244 | false | false | false | false |
Ef/WeatherApp | refs/heads/master | WeatherApp/WeatherApp/Helper/IconHelper.swift | mit | 1 | //
// IconHelper.swift
// WeatherApp
//
// Created by Edgar Lopes on 15/01/2017.
// Copyright © 2017 Edgar Lopes. All rights reserved.
//
import Foundation
import UIKit
class IconHelper {
static func getIcon(_ code: Int) -> UIImage {
var image: UIImage
switch code {
case 200 ... 232:
image = UIImage(named: "Flash")!
break
case 300 ... 321:
image = UIImage(named: "CloudAndSun")!
break
case 500 ... 531:
image = UIImage(named: "Rain")!
break
case 600 ... 622:
image = UIImage(named: "Snow")!
break
case 701 ... 781:
image = UIImage(named: "Haze")!
break
case 800:
image = UIImage(named: "Sun")!
break
case 801 ... 804:
image = UIImage(named: "Cloud")!
break
default:
image = UIImage(named: "Sun")!
}
return image
}
}
| 1260086183d36a5703fd63ba8ffe1a05 | 23.682927 | 54 | 0.481225 | false | false | false | false |
hulinSun/MyRx | refs/heads/master | MyRx/MyRx/Classes/Topic/View/MatchADView.swift | mit | 1 | //
// MatchADView.swift
// MyRx
//
// Created by Hony on 2017/1/4.
// Copyright © 2017年 Hony. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
import Kingfisher
/// 火柴盒的广告轮播View
public class MatchADView<ImageType>: UIView , UIScrollViewDelegate{
typealias ADDidClickClosure = (Int) -> Void
typealias ADViewLoadImageClosure = (UIImageView,ImageType) -> Void
var imageDidClick:ADDidClickClosure?
var loadImage:ADViewLoadImageClosure?
var images = [ImageType]() {
didSet {
pageControl.numberOfPages = images.count
reloadData()
removeTimer()
if images.count > 1 { addTimer() }
}
}
private func removeTimer() {
timer?.invalidate()
timer = nil
}
private func addTimer() {
guard images.count > 0 else {return;}
timer = Timer(timeInterval: 2.5, target: self, selector: #selector(timerScrollImage), userInfo: nil, repeats: true)
RunLoop.current.add(timer!, forMode: RunLoopMode.defaultRunLoopMode)
RunLoop.current.run(mode: RunLoopMode.UITrackingRunLoopMode, before: Date())
}
fileprivate var currentImageArray = [ImageType]()
fileprivate var currentPage = 0
fileprivate var timer:Timer?
fileprivate lazy var scrollView:UIScrollView = {
let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: self.frame.width, height: self.frame.height))
scrollView.contentSize = CGSize(width: self.frame.width * 3, height: self.frame.height)
scrollView.contentOffset = CGPoint(x: self.frame.width, y: 0)
scrollView.isPagingEnabled = true
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.delegate = self
return scrollView
}()
fileprivate lazy var pageControl:UIPageControl = {
let pageWidth = self.frame.width * 0.25
let pageHeight:CGFloat = 20.0
let pageX = self.frame.width - pageWidth - 10.0
let pageY = self.frame.height - 30.0
let pageControl = UIPageControl(frame: CGRect(x: pageX, y: pageY, width: pageWidth, height: pageHeight))
pageControl.isUserInteractionEnabled = false
pageControl.hidesForSinglePage = true
pageControl.currentPageIndicatorTintColor = .red
pageControl.pageIndicatorTintColor = .blue
return pageControl
}()
@objc fileprivate func timerScrollImage() {
reloadData()
scrollView.setContentOffset(CGPoint(x: frame.width * 2.0 , y: 0) , animated: true)
}
override init (frame: CGRect) {
super.init(frame: frame)
addSubview(scrollView)
addSubview(pageControl)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
scrollView.delegate = nil
removeTimer()
}
fileprivate func reloadData() {
//设置页数
pageControl.currentPage = currentPage
//根据当前页取出图片
getDisplayImagesWithCurpage()
//从scrollView上移除所有的subview
scrollView.subviews.forEach({$0.removeFromSuperview()})
for i in 0..<3 {
let frame = CGRect(x: self.frame.width * CGFloat(i), y: 0, width: self.frame.width, height: self.frame.height)
let imageView = UIImageView(frame: frame)
imageView.isUserInteractionEnabled = true
imageView.clipsToBounds = true
scrollView.addSubview(imageView)
imageView.image = UIImage(named: "loading_Image")
loadImage?(imageView,currentImageArray[i])
let tap = UITapGestureRecognizer(target: self, action: #selector(tapImage))
imageView.addGestureRecognizer(tap)
}
}
fileprivate func getDisplayImagesWithCurpage() {
//取出开头和末尾图片在图片数组里的下标
var front = currentPage - 1
var last = currentPage + 1
//如果当前图片下标是0,则开头图片设置为图片数组的最后一个元素
if currentPage == 0 {
front = images.count - 1
}
//如果当前图片下标是图片数组最后一个元素,则设置末尾图片为图片数组的第一个元素
if currentPage == images.count - 1 {
last = 0
}
//如果当前图片数组不为空,则移除所有元素
if currentImageArray.count > 0 {
currentImageArray = [ImageType]()
}
//当前图片数组添加图片
currentImageArray.append(images[front])
currentImageArray.append(images[currentPage])
currentImageArray.append(images[last])
}
@objc fileprivate func tapImage() {
imageDidClick?(currentPage)
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
//如果scrollView当前偏移位置x大于等于两倍scrollView宽度
if scrollView.contentOffset.x >= frame.width * 2.0 {
//当前图片位置+1
currentPage += 1
//如果当前图片位置超过数组边界,则设置为0
if currentPage == images.count {
currentPage = 0
}
reloadData()
//设置scrollView偏移位置
scrollView.contentOffset = CGPoint(x: frame.width, y: 0)
}else if scrollView.contentOffset.x <= 0.0{
currentPage -= 1
if currentPage == -1 {
currentPage = images.count - 1
}
reloadData()
//设置scrollView偏移位置
scrollView.contentOffset = CGPoint(x: frame.width, y: 0)
}
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollView.setContentOffset(CGPoint(x: frame.width, y: 0), animated: true)
}
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
removeTimer()
}
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
addTimer()
}
}
extension Reactive where Base: MatchADView<TopicBanner> {
var banners: UIBindingObserver<Base, [TopicBanner]> {
return UIBindingObserver(UIElement: base) { adView, _ in
adView.loadImage = { ( imageView:UIImageView,imageName:TopicBanner) in
imageView.kf.setImage(with: URL(string: imageName.thumb!), placeholder: UIImage(named: "loading_Image"), options: nil, progressBlock: nil, completionHandler: nil)
}
}
}
}
| cdcd4ec87cc7ee9f72305316ebc1789c | 33.155914 | 178 | 0.623328 | false | false | false | false |
mnewmedia/cordova-plugin-webdav | refs/heads/master | src/ios/wXmlParser.swift | mit | 1 | // http://stackoverflow.com/questions/33156340/parsing-xml-file-in-swift-xcode-v-7-0-1-and-retrieving-values-from-dictionary
class XmlParser: NSObject, NSXMLParserDelegate {
var currentElement: String = ""
var foundCharacters: String = ""
var parsedClass: NSMutableArray = []
weak var parent:XmlParser? = nil // used in childs
let parser = NSXMLParser(contentsOfURL:(NSURL(string:"http://images.apple.com/main/rss/hotnews/hotnews.rss"))!)!
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String]) {
self.currentElement = elementName
if elementName == "d:response" {
let prop = XmlPropstat()
self.parsedClass.addObject(prop)
// now prop class has to parse further, let pop class know who we are so that once hes done XML processing it can return parsing responsibility back
parser.delegate = prop
prop.parent = self
}
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
self.foundCharacters += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
}
} | ef4b8d2d5d9db01885f189c74ce876bd | 39 | 173 | 0.662252 | false | false | false | false |
andyyardley/React | refs/heads/master | ReactTests/RTest.swift | apache-2.0 | 1 | //
// RTest.swift
// placesapp
//
// Created by Andy on 23/10/2015.
// Copyright © 2015 niveusrosea. All rights reserved.
//
import Foundation
enum DefaultError: ErrorType {
case InvalidSelection
}
class RTest
{
init()
{
print("Test Started")
// normal()
// merge()
// combineWithPreviousData()
// test()
print("Test Completed")
}
func test()
{
let values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
// print(values.contentsHash())
let signal = RSignal<[Int], DefaultError>()
signal.dispatch(values)
signal.observe { event in
// print("1: \(event)")
}
signal.dispatch(values)
signal.observe { event in
// print("2: \(event)")
}
signal.dispatch(values)
signal.dispatch([1, 2, 3])
let signal2 = RSignal<[String: Int], DefaultError>()
signal2.observe { event in
// print("3: \(event)")
}
signal2.dispatch(["test": 1])
signal2.dispatch(["test": 1])
// print("test")
}
func normal()
{
let signal = RSignal<[Int], DefaultError>()//.bufferSize(1)
let signal3 = RSignal<[Int], DefaultError>()//.bufferSize(1)
signal.combineWith(signal3).remap { (a, b) -> [Int] in
var output = [Int]()
for var idx = 0; idx < a.count; idx = idx + 1
{
output.append(a[idx] + b[idx])
}
return output
}.observe { event in
switch event {
case let .Next(value):
print("Combined \(value)")
break
case let .Error(error):
print("Combined Error \(error)")
break
default :()
}
}
signal.optionalCombineWith(signal3).observe { event in
switch event {
case let .Next(value):
print("Optional Combined \(value)")
break
case let .Error(error):
print("Optional Combined Error \(error)")
break
default :()
}
}
let _ = signal.observe { event in
switch event {
case let .Next(value):
print("Event1 Next \(value)")
break
case .Interrupted:
break
case let .Error(error):
print("Event1 Error \(error)")
break
case .Completed:
break
case .Processing:
break
default: ()
}
}
let signal2 = signal.remap { values -> [String] in
var output = [String]()
for value in values
{
output.append("V \(value + 1)")
}
return output
}
let _ = signal2.observe { event in
switch event {
case let .Next(value):
print("Event2 Next \(value)")
break
case .Interrupted:
break
case let .Error(error):
print("Event2 Error \(error)")
break
case .Completed:
break
case .Processing:
break
default: ()
}
}
signal.dispatch([1, 2, 3, 4, 6])
signal3.dispatch([5, 4, 3, 2, 0])
let _ = signal2.observe { event in
switch event {
case let .Next(value):
print("Event3 Next \(value)")
break
case .Interrupted:
break
case let .Error(error):
print("Event3 Error \(error)")
break
case .Completed:
break
case .Processing:
break
default: ()
}
}
signal.clearBuffer()
let _ = signal2.observe { event in
switch event {
case let .Next(value):
print("Event4 Next \(value)")
break
case .Interrupted:
break
case let .Error(error):
print("Event4 Error \(error)")
break
case .Completed:
break
case .Processing:
break
default: ()
}
}
signal.error(DefaultError.InvalidSelection)
signal3.error(.InvalidSelection)
}
func combineWithPreviousData()
{
let signal1 = RSignal<Int, DefaultError>()//.bufferSize(1)
let signal2 = RSignal<Int, DefaultError>()//.bufferSize(1)
signal1.dispatch(5)
signal2.dispatch(5)
signal1.combineWith(signal2).observe { event in
switch event {
case let .Next((int1, int2)):
print("\(int1), \(int2)")
default: ()
}
}
signal1.dispatch(2)
signal2.dispatch(2)
}
func merge()
{
let signal = RSignal<Int, DefaultError>()
let signal2 = signal.merge { values -> Int in
var output = 0
for value in values
{
output += value
}
return output
}//.bufferSize(1)
signal.dispatch(5)
signal.dispatch(2)
signal.dispatch(3)
signal.completed()
signal2.observe { event in
switch event {
case let .Next(value):
print("Val : \(value)")
break
default: ()
}
}.dispose()
print("Yello")
}
} | bad55bdedd52015ef53937a90b712ace | 23.505976 | 68 | 0.414309 | false | false | false | false |
jessesquires/swift-proposal-analyzer | refs/heads/master | swift-proposal-analyzer.playground/Pages/SE-0197.xcplaygroundpage/Contents.swift | mit | 1 | /*:
# Adding in-place `removeAll(where:)` to the Standard Library
* Proposal: [SE-0197](0197-remove-where.md)
* Author: [Ben Cohen](https://github.com/airspeedswift)
* Review Manager: [John McCall](https://github.com/rjmccall)
* Status: **Accepted with Revisions**
* Implementation: [apple/swift#11576](https://github.com/apple/swift/pull/11576)
* Review: [Thread](https://forums.swift.org/t/se-0197-add-in-place-remove-where/8872)
* Previous Revision: [1](https://github.com/apple/swift-evolution/blob/feec7890d6c193e9260ac9905456f25ef5656acd/proposals/0197-remove-where.md)
## Introduction
It is common to want to remove all occurrences of a certain element from a
collection. This proposal is to add a `removeAll` algorithm to the
standard library, which will remove all entries in a collection in-place
matching a given predicate.
## Motivation
Removing all elements matching some criteria is a very common operation.
However, it can be tricky to implement correctly and
efficiently.
The easiest way to achieve this effect in Swift 3 is to use `filter` and assign
back, negating the thing you want to remove (because `filter` takes a closure
of items to "keep"):
```swift
var nums = [1,2,3,4,5]
// remove odd elements
nums = nums.filter { !isOdd($0) }
```
In addition to readability concerns, this has two performance problems: fresh
memory allocation, and a copy of all the elements in full even if none need to
be removed.
The alternative is to open-code a `for` loop. The simplest performant solution
is the "shuffle-down" approach. While not especially complex, it is certainly
non-trivial:
```swift
if var i = nums.index(where: isOdd) {
var j = i + 1
while j != nums.endIndex {
let e = nums[j]
if !isOdd(nums[j]) {
nums[i] = nums[j]
i += 1
}
j += 1
}
nums.removeSubrange(i...)
}
```
Possibilities for logic and performance errors abound. There are probably some
in the above code.
Additionally, this approach does not work for range-replaceable collections
that are _not_ mutable i.e. collections that can replace subranges, but can't
guarantee replacing a single element in constant time. `String` is the most
important example of this, because its elements (graphemes) are variable width.
## Proposed solution
Add the following method to `RangeReplaceableCollection`:
```swift
nums.removeAll(where: isOdd)
```
The default implementation will use the protocol's `init()` and `append(_:)`
operations to implement a copy-based version. Collections which also conform to
`MutableCollection` will get the more efficient "shuffle-down" implementation,
but still require `RangeReplaceableCollection` as well because of the need to
trim at the end. Other types may choose
Collections which are range replaceable but _not_ mutable (like `String`) will
be able to implement their own version which makes use of their internal
layout. Collections like `Array` may also implement more efficient versions
using memory copying operations.
Since `Dictionary` and `Set` would benefit from this functionality as well, but
are not range-replaceable, they should be given concrete implementations for
consistency.
## Detailed design
Add the following to `RangeReplaceableCollection`:
```swift
protocol RangeReplaceableCollection {
/// Removes every element satisfying the given predicate from the collection.
mutating func removeAll(where: (Iterator.Element) throws -> Bool) rethrows
}
extension RangeReplaceableCollection {
mutating func removeAll(where: (Iterator.Element) throws -> Bool) rethrows {
// default implementation similar to self = self.filter
}
}
```
Other protocols or types may also have custom implementations for a faster
equivalent. For example `RangeReplaceableCollection where Self:
MutableCollection` can provide a more efficient non-allocating default
implementation. `String` is also likely to benefit from a custom implementation.
## Source compatibility
This change is purely additive so has no source compatibility consequences.
## Effect on ABI stability
This change is purely additive so has no ABI stability consequences.
## Effect on API resilience
This change is purely additive so has no API resilience consequences.
## Alternatives considered
`removeAll(where:)` takes a closure with `true` for elements to remove.
`filter` takes a closure with elements to keep. In both cases, `true` is the
"active" case, so likely to be what the user wants without having to apply a
negation. The naming of `filter` is unfortunately ambiguous as to whether it's
a removing or keeping operation, but re-considering that is outside the scope
of this proposal.
Several collection methods in the standard library (such as `index(where:)`)
have an equivalent for collections of `Equatable` elements. A similar addition
could be made that removes every element equal to a given value. This could
easily be done as a further additive proposal later.
The initial proposal of this feature named it `remove(where:)`. During review,
it was agreed that this was unnecessarily ambiguous about whether all the
matching elements should be removed or just the first, and so the method was
renamed to `removeAll(where:)`.
----------
[Previous](@previous) | [Next](@next)
*/
| e3a5717650368803b7b51488247d33ba | 34.755102 | 143 | 0.767314 | false | false | false | false |
apple/swift | refs/heads/main | test/SILOptimizer/Inputs/cross-module/default-module.swift | apache-2.0 | 2 |
import Submodule
import PrivateCModule
public func incrementByThree(_ x: Int) -> Int {
return incrementByOne(x) + 2
}
public func incrementByThreeWithCall(_ x: Int) -> Int {
return incrementByOneNoCMO(x) + 2
}
public func submoduleKlassMember() -> Int {
let k = SubmoduleKlass()
return k.i
}
public final class ModuleKlass {
public var i: Int
public init() {
i = 27
}
}
public func moduleKlassMember() -> Int {
let k = ModuleKlass()
return k.i
}
public struct ModuleStruct {
public static var publicFunctionPointer: (Int) -> (Int) = incrementByThree
public static var privateFunctionPointer: (Int) -> (Int) = { $0 }
}
public func callPrivateCFunc() -> Int {
return Int(privateCFunc())
}
public func usePrivateCVar() -> Int {
return Int(privateCVar);
}
| d56ff3f17f737e2a9ccb5167a4e73f2a | 17.857143 | 76 | 0.689394 | false | false | false | false |
Nyx0uf/MPDRemote | refs/heads/master | src/iOS/views/AutoScrollLabel.swift | mit | 1 | // AutoScrollLabel.swift
// Copyright (c) 2017 Nyx0uf
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
private let kNYXLabelSpacing = CGFloat(20.0)
enum ScrollDirection
{
case left
case right
}
final class AutoScrollLabel : UIView
{
/// Scroll direction
public var direction = ScrollDirection.left
{
didSet
{
scrollLabelIfNeeded()
}
}
/// Scroll speed (px per second)
public var scrollSpeed = 30.0
{
didSet
{
scrollLabelIfNeeded()
}
}
/// Pause (seconds)
public var pauseInterval = 4.0
/// Is scrolling flag
private(set) var isScrolling = false
/// Fade length
public var fadeLength = CGFloat(8.0)
{
didSet
{
if fadeLength != oldValue
{
refreshLabels()
applyGradientMaskForFadeLength(fadeLengthIn: fadeLength, fade: false)
}
}
}
// MARK: UILabel properties
/// Text
public var text: String?
{
get
{
return self.mainLabel.text
}
set
{
self.setText(text: newValue, refresh: true)
}
}
/// Text color
public var textColor: UIColor!
{
get
{
return self.mainLabel.textColor
}
set
{
self.mainLabel.textColor = newValue
self.secondaryLabel.textColor = newValue
}
}
/// Font
public var font: UIFont!
{
get
{
return self.mainLabel.font
}
set
{
self.mainLabel.font = newValue
self.secondaryLabel.font = newValue
self.refreshLabels()
self.invalidateIntrinsicContentSize()
}
}
/// Text align (only when not auto-scrolling)
public var textAlignment = NSTextAlignment.left
/// Scrollview
private(set) var scrollView: UIScrollView!
/// Labels
private var mainLabel: UILabel!
private var secondaryLabel: UILabel!
// MARK: UIView Override
public override var frame: CGRect
{
get
{
return super.frame
}
set
{
super.frame = newValue
didChangeFrame()
}
}
public override var bounds: CGRect
{
get
{
return super.bounds
}
set
{
super.bounds = newValue
didChangeFrame()
}
}
public override var intrinsicContentSize: CGSize
{
get
{
return CGSize(width: 0.0, height: self.mainLabel.intrinsicContentSize.height)
}
}
// MARK: - Initializers
public override init(frame: CGRect)
{
super.init(frame: frame)
self.isUserInteractionEnabled = false
self.clipsToBounds = true
self.scrollView = UIScrollView(frame: self.bounds)
self.scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.scrollView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.isScrollEnabled = false
self.addSubview(self.scrollView)
// Create labels
self.mainLabel = UILabel()
self.mainLabel.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.scrollView.addSubview(self.mainLabel)
self.secondaryLabel = UILabel()
self.secondaryLabel.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.scrollView.addSubview(self.secondaryLabel)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.isUserInteractionEnabled = false
self.clipsToBounds = true
self.scrollView = UIScrollView(frame: self.bounds)
self.scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.scrollView.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.scrollView.showsVerticalScrollIndicator = false
self.scrollView.showsHorizontalScrollIndicator = false
self.scrollView.isScrollEnabled = false
self.addSubview(self.scrollView)
// Create labels
self.mainLabel = UILabel()
self.mainLabel.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.scrollView.addSubview(self.mainLabel)
self.secondaryLabel = UILabel()
self.secondaryLabel.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
self.scrollView.addSubview(self.secondaryLabel)
}
// MARK: - Private
private func didChangeFrame()
{
refreshLabels()
applyGradientMaskForFadeLength(fadeLengthIn: fadeLength, fade: isScrolling)
}
// MARK: - Public
public func setText(text: String?, refresh: Bool)
{
if text == self.text
{
return
}
self.mainLabel.text = text
self.secondaryLabel.text = text
if refresh
{
refreshLabels()
}
}
@objc public func scrollLabelIfNeeded()
{
DispatchQueue.main.async {
if String.isNullOrWhiteSpace(self.text)
{
return
}
let labelWidth = self.mainLabel.bounds.width
if labelWidth <= self.bounds.width
{
return
}
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(AutoScrollLabel.scrollLabelIfNeeded), object: nil)
self.scrollView.layer.removeAllAnimations()
let scrollLeft = (self.direction == .left)
self.scrollView.contentOffset = scrollLeft ? .zero : CGPoint(x: labelWidth + kNYXLabelSpacing, y: 0)
// Scroll animation
let duration = Double(labelWidth) / self.scrollSpeed
UIView.animate(withDuration: duration, delay: self.pauseInterval, options: [.curveLinear, .allowUserInteraction], animations: {() -> Void in
self.scrollView.contentOffset = scrollLeft ? CGPoint(x: labelWidth + kNYXLabelSpacing, y: 0) : .zero
}) { finished in
self.isScrolling = false
self.applyGradientMaskForFadeLength(fadeLengthIn: self.fadeLength, fade: false)
if finished
{
self.performSelector(inBackground: #selector(AutoScrollLabel.scrollLabelIfNeeded), with: nil)
}
}
}
}
private func refreshLabels()
{
if mainLabel == nil
{
return
}
mainLabel.sizeToFit()
secondaryLabel.sizeToFit()
var frame1 = mainLabel.frame
frame1.origin = .zero
frame1.size.height = bounds.height
mainLabel.frame = frame1
var frame2 = secondaryLabel.frame
frame2.origin = CGPoint(mainLabel.bounds.width + kNYXLabelSpacing, 0);
frame2.size.height = bounds.height
secondaryLabel.frame = frame2
scrollView.contentOffset = .zero
scrollView.layer.removeAllAnimations()
// If label is bigger than width => scroll
if mainLabel.bounds.width > bounds.width
{
secondaryLabel.isHidden = false
var size = CGSize.zero
size.width = mainLabel.bounds.width + bounds.width + kNYXLabelSpacing
size.height = self.bounds.height
scrollView.contentSize = size
applyGradientMaskForFadeLength(fadeLengthIn: fadeLength, fade: isScrolling)
scrollLabelIfNeeded()
}
else
{
secondaryLabel.isHidden = true
scrollView.contentSize = bounds.size
mainLabel.frame = bounds
mainLabel.isHidden = false
mainLabel.textAlignment = textAlignment
scrollView.layer.removeAllAnimations()
applyGradientMaskForFadeLength(fadeLengthIn: 0, fade: false)
}
}
private func applyGradientMaskForFadeLength(fadeLengthIn: CGFloat, fade: Bool)
{
if mainLabel == nil
{
return
}
let fadeLength = (mainLabel.bounds.width <= bounds.width) ? 0 : fadeLengthIn
if fadeLength != 0
{
let gradientMask = CAGradientLayer()
gradientMask.bounds = layer.bounds
gradientMask.position = CGPoint(x: bounds.midX, y: bounds.midY)
gradientMask.shouldRasterize = true
gradientMask.rasterizationScale = UIScreen.main.scale
gradientMask.startPoint = CGPoint(x: 0, y: frame.midY)
gradientMask.endPoint = CGPoint(x: 1, y: frame.midY)
gradientMask.colors = [#colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor, #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor, #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1).cgColor, #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0).cgColor]
// Calcluate fade
let fadePoint = fadeLength / bounds.width
var leftFadePoint = fadePoint
var rightFadePoint = 1 - fadePoint
if !fade
{
switch (direction)
{
case .left:
leftFadePoint = 0
case .right:
leftFadePoint = 0
rightFadePoint = 1
}
}
gradientMask.locations = [NSNumber(value: 0), NSNumber(value: Double(leftFadePoint)), NSNumber(value: Double(rightFadePoint)), NSNumber(value: 1)]
CATransaction.begin()
CATransaction.setDisableActions(true)
layer.mask = gradientMask
CATransaction.commit()
}
else
{
layer.mask = nil
}
}
}
| fc4173fd6df959b190dd59423711f85c | 24.657382 | 265 | 0.718272 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/MessageResponse.swift | mit | 1 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** A response from the Conversation service. */
public struct MessageResponse: Decodable {
/// The user input from the request.
public var input: MessageInput?
/// An array of intents recognized in the user input, sorted in descending order of confidence.
public var intents: [RuntimeIntent]
/// An array of entities identified in the user input.
public var entities: [RuntimeEntity]
/// Whether to return more than one intent. A value of `true` indicates that all matching intents are returned.
public var alternateIntents: Bool?
/// State information for the conversation.
public var context: Context
/// Output from the dialog, including the response to the user, the nodes that were triggered, and log messages.
public var output: OutputData
/// Additional properties associated with this model.
public var additionalProperties: [String: JSON]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case input = "input"
case intents = "intents"
case entities = "entities"
case alternateIntents = "alternate_intents"
case context = "context"
case output = "output"
static let allValues = [input, intents, entities, alternateIntents, context, output]
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
input = try container.decodeIfPresent(MessageInput.self, forKey: .input)
intents = try container.decode([RuntimeIntent].self, forKey: .intents)
entities = try container.decode([RuntimeEntity].self, forKey: .entities)
alternateIntents = try container.decodeIfPresent(Bool.self, forKey: .alternateIntents)
context = try container.decode(Context.self, forKey: .context)
output = try container.decode(OutputData.self, forKey: .output)
let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self)
additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues)
}
}
| af7ff7645d6b942dfd51251fdb89a15d | 41.060606 | 116 | 0.715058 | false | false | false | false |
CodaFi/swift-compiler-crashes | refs/heads/master | crashes-duplicates/00170-swift-parser-skipsingle.swift | mit | 12 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func i(f: g) -> <j>(() -> j) -> g { func g
k, l {
typealias l = m<k<m>, f>
}
func ^(a: BooleanType, Bool) -> Bool {
return !(a)
}
func b(c) -> <d>(() -> d) {
}
func q(v: h) -> <r>(() -> r) -> h {
n { u o "\(v): \(u())" }
}
struct e<r> {
j p: , () -> ())] = []
}
protocol p {
}
protocol m : p {
}
protocol v : p {
}
protocol m {
v = m
}
func s<s : m, v : m u v.v == s> (m: v) {
}
func s<v : m u v.v == v> (m: v) {
}
s( {
({})
}
t
func f<e>() -> (e, e -> e) -> e {
e b e.c = {}
{
e)
{
f
}
}
protocol f {
class func c()
}
class e: f {
class func c
}
}
protocol A {
func c()l k {
func l() -> g {
m ""
}
}
class C: k, A {
j func l()q c() -> g {
m ""
}
}
func e<r where r: A, r: k>(n: r) {
n.c()
}
protocol A {
typealias h
}
c k<r : A> {
p f: r
p p: r.h
}
protocol C l.e()
}
}
class o {
typealias l = l
protocol a {
}
protocol h : a {
}
protocol k : a {
}
protocol g {
j n = a
}
struct n : g {
j n = h
}
func i<h : h, f : g m f.n == h> (g: f) {
}
func i<n : g m n.n = o) {
}
let k = a
k()
h
protocol k : h { func h
k
func f(k: Any, j: Any) -> (((Any, Any) -> Any) -> c
k)
func c<i>() -> (i, i -> i) -> i {
k b k.i = {
}
{
i) {
k }
}
protocol c {
class func i()
}
class k: c{ class func i {
}
class i {
func d((h: (Any, AnyObject)) {
d(h)
}
}
d
h)
func d<i>() -> (i, i -> i) -> i {
i j i.f = {
}
protocol d {
class func f()
}
class i: d{ class func f {}
protocol a {
}
protocol b : a {
}
protocol c : a {
}
protocol d {
typealias f = a
}
struct e : d {
typealias f = b
}
func i<j : b, k : d where k.f == j> (n: k) {
}
func i<l : d where l.f == c> (n: l) {
}
i(e())
class l {
func f((k, l() -> f
}
class d
}
class i: d, g {
l func d() -> f {
m ""
}
}
}
func m<j n j: g, j: d
let l = h
l()
f
protocol l : f { func f
protocol g
func g<h>() -> (h, h -> h) -> h {
f f: ((h, h -> h) -> h)!
j f
}
protocol f {
class func j()
}
struct i {
f d: f.i
func j() {
d.j()
}
}
class g {
typealias f = f
}
func g(f: Int = k) {
}
let i = g
class k {
func l((Any, k))(m }
}
func j<f: l: e -> e = {
{
l) {
m }
}
protocol k {
class func j()
}
class e: k{ class func j
struct c<d : SequenceType> {
var b: [c<d>] {
return []
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicType.c()
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> A var d: b.Type
func e() {
d.e()
}
}
b
protocol c : b { func b
otocol A {
E == F>(f: B<T>)
}
struct }
}
struct c<d : SequenceType> {
var b: d
}
func a<d>() -> [c<d>] {
return []
}
func ^(d: e, Bool) -> Bool {g !(d)
}
protocol d {
f func g()
f e: d {
f func g() { }
}
(e() h d).i()
e
protocol g : e { func e
func a(b: Int = 0) {
}
let c = a
c()
var f = 1
var e: Int -> Int = {
return $0
}
let d: Int = { c, b in
}(f, e)
func m<u>() -> (u, u -> u) -> u {
p o p.s = {
}
{
u) {
o }
}
s m {
class func s()
}
class p: m{ class func s {}
s p {
func m() -> String
}
class n {
func p() -> String {
q ""
}
}
class e: n, p {
v func> String {
q ""
}
{
r m = m
}
func s<o : m, o : p o o.m == o> (m: o) {
}
func s<v : p o v.m == m> (u: String) -> <t>(() -> t) -
func p<p>() -> (p, p -> p) -> p {
l c l.l = {
}
{
p) {
(e: o, h:o) -> e
})
}
j(k(m, k(2, 3)))
func l(p: j) -> <n>(() -> n
struct c<d: SequenceType, b where Optional<b> == d.Generator.Element>
d = i
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
typealias i
}
protocol e {
class func i()
}
i
(d() as e).j.i()
d
protocol i : d { func d
class k<g>: d {
var f: g
init(f: g) {
self.f = f
l. d {
typealias i = l
typealias j = j<i<l>, i>
}
class j {
typealias d = d
struct A<T> {
let a: [(T, () -> ())] = []
}
func b<d-> d { class d:b class b
class A<T : A> {
}
func c<d {
enum c {
func e
var _ = e
}
}
protocol a {
class func c()
}
class b: a {
class func c() { }
}
(b() as a).dynamicl A {
{
typealias b = b
d.i = {
}
{
g) {
h }
}
protocol f {
class func i()
}}
func f<m>() -> (m, m -> m) -> m {
e c e.i = {
}
{
m) {
n }
}
protocol f {
class func i()
}
class e: f{ class func i {}
func n<j>() -> (j, j -> j) -> j {
var m: ((j> j)!
f m
}
protocol k {
typealias m
}
struct e<j : k> {n: j
let i: j.m
}
l
func m(c: b) -> <h>(() -> h) -> b {
f) -> j) -> > j {
l i !(k)
}
d
l)
func d<m>-> (m, m -
import Foundation
class Foo<T>: NSObject {
var foo: T
init(foo: T) {
B>(t: T) {
t.c()
} x
x) {
}
class a {
var _ = i() {
}
}
a=1 as a=1
func k<q>() -> [n<q>] {
r []
}
func k(l: Int = 0) {
}
n n = k
n()
func n<q {
l n {
func o
o _ = o
}
}
func ^(k: m, q) -> q {
r !(k)
}
protocol k {
j q
j o = q
j f = q
}
class l<r : n, l : n p r.q == l> : k {
}
class l<r, l> {
}
protocol n {
j q
}
protocol k : k {
}
class k<f : l, q : l p f.q == q> {
}
protocol l {
j q
j o
}
struct n<r : l>
func k<q {
enum k {
func j
var _ = j
}
}
class x {
s m
func j(m)
}
struct j<u> : r {
func j(j: j.n) {
}
}
enum q<v> { let k: v
let u: v.l
}
protocol y {
o= p>(r: m<v>)
}
struct D : y {
s p = Int
func y<v k r {
s m
}
class y<D> {
w <r:
func j<v x: v) {
x.k()
}
func x(j: Int = a) {
}
let k = x
func b((Any, e))(e: (Any) -> <d>(()-> d) -> f
func a(x: Any, y: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(m: (Any, Any) -> Any) -> Any in
return m(x, y)
}
}
func b(z: (((Any, Any) -> Any) -> Any)) -> Any {
return z({
(p: Any, q:Any) -> Any in
return p
})
}
b(a(1, a(2, 3)))
protocol f : f {
}
func h<d {
enum h {
func e
var _ = e
}
}
protocol e {
e func e()
}
struct h {
var d: e.h
func e() {
d.e()
}
}
protocol f {
i []
}
func f<g>() -> (g, g -> g) -> g
class A<T : A> n = {
return $u
}
l o: n = { (d: n, o: n -> n) -> n q
return o(d)
}
import Foundation
class m<j>: NSObject {
var h: j
g -> k = l $n
}
b f: _ = j() {
}
}
func k<g {
enum k {
func l
var _ = l
func o() as o).m.k()
func p(k: b) -> <i>(() -> i) -> b {
n { o f "\(k): \(o())" }
}
struct d<d : n, o:j n {
l p
}
protocol o : o {
}
func o<
class a<f : b, g : b where f.d == g> {
}
protocol b {
typealias d
typealias e
}
struct c<h : b> : b {
typealias d = h
typealias e = a<c<h>, d>
}
func c<g>() -> (g, g -> g) -> g {
d b d.f = {
}
{
g) {
i }
}
i c {
class func f()
}
class d: c{ class func f {}
struct d<c : f,f where g.i == c.i>
struct l<e : SequenceType> {
l g: e
}
func h<e>() -> [l<e>] {
f []
}
func i(e: g) -> <j>(() -> j) -> k
struct c<e> {
let d: [( h
}
func b(g: f) -> <e>(()-> e) -> i
h
}
func e<l {
enum e {
func e
j {
class func n()
}
class l: j{ k() -> ())
}
({})
func j<o : BooleanType>(l: o) {
}
j(j q BooleanType)
func p(l: Any, g: Any) -> (((Any, Any) -> Any) -> Any) {
return {
(p: (Any, Any) -> Any) -> Any in
func n<n : l,) {
}
n(e())
e
func a<T>() {
enum b {
case c
}
}
o
class w<r>: c {
init(g: r) {
n.g = g
s.init()
(t: o
struct t : o {
p v = t
}
q t<where n.v == t<v : o u m : v {
}
struct h<t, j: v where t.h == j
f> {
c(d ())
}
func b(e)-> <d>(() -> d)
func f<T : BooleanType>(b: T) {
}
f(true as BooleanType)
class A: A {
}
class B : C {
}
typealias C = B
protocol A {
typealias E
}
struct B<T : As a {
typealias b = b
}
func a<T>() {f {
class func i()
}
class d: f{ class func i {}
func f() {
({})
}
func prefix(with: String) -> <T>(() -> T) -> String {
return { g in "\(with): \(g())" }
}
protocol a : a {
}
class j {
func y((Any, j))(v: (Any, AnyObject)) {
y(v)
}
}
func w(j: () -> ()) {
}
class v {
l _ = w() {
}
}
({})
func v<x>() -> (x, x -> x) -> x {
l y j s<q : l, y: l m y.n == q.n> {
}
o l {
u n
}
y q<x> {
s w(x, () -> ())
}
o n {
func j() p
}
class r {
func s() -> p {
t ""
}
}
class w: r, n {
k v: ))] = []
}
class n<x : n>
w
class x<u>: d {
l i: u
init(i: u) {
o.i = j {
r { w s "\(f): \(w())" }
}
protoc
protocol f : b { func b
() {
g g h g
}
}
func e(i: d) -> <f>(() -> f)>
import Foundation
class k<f>: NSObject {
d e: f
g(e: f) {
j h.g()
}
}
d
protocol i : d { func d
i
b
protocol d : b { func b
func d(e: = { (g: h, f: h -> h) -> h in
return f(g)
}
}
}
class b<i : b> i: g{ func c {}
e g {
: g {
h func i() -> }
struct j<l : o> {
k b: l
}
func a<l>() -> [j<l>] {
return []
}
f
k)
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
class func n()
}
class l: f{ class func n {}
func a<i>() {
b b {
l j
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
typealias l
typealias k
}
struct j<n : b> : b {
typealias l = n
typealias k = a<j<n>, l>
}
protocol a {
typealias d
typealias e = d
typealias f = d
}
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
typealias g
}
a=1 as a=1
enum S<T> {
case C(T, () -> ())
}
n)
func f<o>() -> (o, o -> o) -> o {
o m o.j = {
}
{
o) {
r }
}
p q) {
}
o m = j
m()
class m {
func r((Any, m))(j: (Any, AnyObject)) {
r(j)
}
}
func m<o {
r m {
func n
n _ = n
}
}
class k<l : k
<c b:
func b<c {
enum b {
func b
var _ = b
func n<p>() -> (p, p -> p) -> p {
b, l]
g(o(q))
h e {
j class func r()
}
class k: h{ class func r {}
var k = 1
var s: r -> r t -> r) -> r m
u h>] {
u []
}
func r(e: () -> ()) {
}
class n {
var _ = r()
| e2857ed58534f044e9ab4044efd8b203 | 12.103979 | 87 | 0.405858 | false | false | false | false |
phillips07/StudyCast | refs/heads/master | StudyCast/MainScreenController.swift | mit | 1 | //
// ViewController.swift
// StudyCastv2
//
// Created by Dennis on 2016-11-03.
// Copyright © 2016 Apollo. All rights reserved.
//
import UIKit
import Firebase
class MainScreenController: UITableViewController {
var userCourses = [String]()
var userNotifications = [[String]]()
var notificationSectionHeaders = [String]()
var notificationDataSet: [[NotificationSender]] = [[]]
var notificationSenders = [NotificationSender]()
var userName = String()
override func viewDidLoad() {
super.viewDidLoad()
let image = UIImage(named: "SettingsIcon")
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: image, style: .plain, target: self, action: #selector(handleSettings))
tableView.register(GroupCell.self, forCellReuseIdentifier: "userCell")
tableView.register(Header.self, forHeaderFooterViewReuseIdentifier: "headerId")
tableView.sectionHeaderHeight = 50
self.navigationController?.navigationBar.barTintColor = UIColor(r: 61, g: 91, b: 151)
self.tabBarController?.tabBar.barTintColor = UIColor(r: 61, g: 91, b: 151)
//code to render the original icon (remove applied gray mask which is default)
let aTabArray: [UITabBarItem] = (self.tabBarController?.tabBar.items)!
for item in aTabArray {
item.image = item.image?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
item.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0)
}
if FIRAuth.auth()?.currentUser?.uid == nil {
perform(#selector(handleLogout), with: nil, afterDelay: 0)
}
userCourses.removeAll()
notificationDataSet.removeAll()
notificationSectionHeaders.removeAll()
fetchNotifications()
fetchCurrentName()
tableView.tableFooterView = UIView()
self.tableView.reloadData()
}
override func viewWillAppear(_ animated: Bool) {
if FIRAuth.auth()?.currentUser?.uid == nil {
perform(#selector(handleLogout), with: nil, afterDelay: 0)
} else {
//notificationDataSet.removeAll()
//notificationSectionHeaders.removeAll()
fetchNameSetupNavBar()
fetchClasses()
fetchNotifications()
fetchCurrentName()
}
}
func fetchNameSetupNavBar() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
FIRDatabase.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let userDictionary = snapshot.value as? [String: AnyObject] {
self.navigationItem.rightBarButtonItem?.tintColor = UIColor.white
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.white
let screenSize: CGRect = UIScreen.main.bounds
let titleView = UIView()
titleView.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: 40)
let containerView = UIView()
containerView.translatesAutoresizingMaskIntoConstraints = false
titleView.addSubview(containerView)
containerView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
let profileImageView = UIImageView()
profileImageView.translatesAutoresizingMaskIntoConstraints = false
profileImageView.contentMode = .scaleAspectFill
profileImageView.layer.cornerRadius = 20
profileImageView.clipsToBounds = true
if let profileImageUrl = userDictionary["profileImage"] as? String{
profileImageView.loadImageUsingCacheWithUrlString(urlString: profileImageUrl)
}
containerView.addSubview(profileImageView)
profileImageView.leftAnchor.constraint(equalTo: containerView.leftAnchor).isActive = true
profileImageView.centerYAnchor.constraint(equalTo: containerView.centerYAnchor).isActive = true
profileImageView.widthAnchor.constraint(equalToConstant: 40).isActive = true
profileImageView.heightAnchor.constraint(equalToConstant: 40).isActive = true
let nameLabel = UILabel()
containerView.addSubview(nameLabel)
nameLabel.text = userDictionary["name"] as? String
nameLabel.translatesAutoresizingMaskIntoConstraints = false
nameLabel.leftAnchor.constraint(equalTo: profileImageView.rightAnchor, constant: 8).isActive = true
nameLabel.centerYAnchor.constraint(equalTo: profileImageView.centerYAnchor).isActive = true
nameLabel.rightAnchor.constraint(equalTo: containerView.rightAnchor).isActive = true
nameLabel.heightAnchor.constraint(equalTo: profileImageView.heightAnchor).isActive = true
nameLabel.textColor = UIColor.white
containerView.rightAnchor.constraint(equalTo: titleView.rightAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: titleView.centerYAnchor).isActive = true
self.navigationItem.titleView = titleView
}
}, withCancel: nil)
}
func fetchNotifications() {
notificationDataSet.removeAll()
notificationSectionHeaders.removeAll()
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
FIRDatabase.database().reference().child("users").child(uid).child("notifications").observe(.childAdded, with: { (snapshot) in
let numClassSections = self.notificationSectionHeaders.count
let notificationSender = NotificationSender()
var duplicate = false
if let notificationsDictionary = snapshot.value as? [String: AnyObject] {
notificationSender.senderName = notificationsDictionary["senderName"] as? String
notificationSender.groupName = notificationsDictionary["groupName"] as? String
notificationSender.gid = notificationsDictionary["gid"] as? String
notificationSender.senderName = notificationsDictionary["senderName"] as? String
notificationSender.className = notificationsDictionary["class"] as? String
notificationSender.groupPictureURL = notificationsDictionary["groupPictureURL"] as? String
notificationSender.nid = notificationsDictionary["nid"] as? String
}
for i in self.notificationDataSet {
for g in i {
if g.gid == notificationSender.gid {
duplicate = true
}
}
}
if notificationSender.className == nil {
}
else if !duplicate {
if numClassSections == 0 {
self.notificationSectionHeaders.append(notificationSender.className!)
self.notificationDataSet.append([notificationSender])
} else {
var i = 0
var added = false
for g in self.notificationSectionHeaders {
if(notificationSender.className)! == g {
self.notificationDataSet[i].append(notificationSender)
added = true
}
i += 1
}
if !added {
self.notificationSectionHeaders.append(notificationSender.className!)
self.notificationDataSet.append([notificationSender])
}
}
self.tableView.reloadData()
} else if duplicate {
// let noteRef = FIRDatabase.database().reference().child("users").child(uid).child("notifications").child(notificationSender.nid!)
// noteRef.removeValue()
// duplicate = false
// print("removed?")
// self.notificationDataSet.removeAll()
// self.notificationSectionHeaders.removeAll()
}
})
}
func fetchClasses() {
userCourses.removeAll()
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
FIRDatabase.database().reference().child("users").child(uid).child("courses").observe(.childAdded, with: { (snapshot) in
self.userCourses.append(snapshot.value as! String)
self.tableView.reloadData()
})
}
func fetchCurrentName() {
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
FIRDatabase.database().reference().child("users").child(uid).child("name").observe(.value, with: { (snapshot) in
if let userN = snapshot.value as? String {
self.userName = userN
}
else {
self.handleLogout()
}
})
}
func handleLogout() {
do {
try FIRAuth.auth()?.signOut()
} catch let logoutError {
print(logoutError)
}
let loginController = LoginController()
//let loginController = ClassSelectController()
present(loginController, animated: false, completion: nil)
}
func handleSettings(){
let settingsController = SettingsController()
//let settingsController = UserListController()
let settingsNavController = UINavigationController(rootViewController: settingsController)
present(settingsNavController, animated: true, completion: nil)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection
section: Int) -> Int {
return notificationDataSet[section].count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath) as! GroupCell
if notificationDataSet.count != 0 {
cell.textLabel?.numberOfLines = 2;
cell.textLabel?.text = notificationDataSet[indexPath.section][indexPath.row].senderName! +
" has invited you to group \n" + notificationDataSet[indexPath.section][indexPath.row].groupName!
if let groupImageURL = notificationDataSet[indexPath.section][indexPath.row].groupPictureURL {
let url = NSURL(string: groupImageURL)
URLSession.shared.dataTask(with: url! as URL, completionHandler: { (data, response, error) in
if error != nil {
print(error!)
return
}
DispatchQueue.main.async {
cell.profileImageView.image = UIImage(data: data!)
self.tableView.reloadData()
}
}).resume()
}
}
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let header = tableView.dequeueReusableHeaderFooterView(withIdentifier: "headerId") as! Header
if notificationDataSet.count != 0 {
header.nameLabel.text = notificationSectionHeaders[section]
}
return header
}
override func numberOfSections(in tableView: UITableView) -> Int {
if notificationSectionHeaders.count > 0 {
tableView.separatorStyle = .singleLine
tableView.backgroundView = nil
} else {
let noDataLabel: UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: tableView.bounds.size.width, height: tableView.bounds.size.height))
noDataLabel.text = "You have no notifications"
noDataLabel.textColor = UIColor(r: 61, g: 91, b: 151)
noDataLabel.textAlignment = .center
tableView.backgroundView = noDataLabel
tableView.separatorStyle = .none
}
return notificationSectionHeaders.count
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let uid = FIRAuth.auth()?.currentUser?.uid else {
return
}
if notificationDataSet.count > 0 {
let alertController = UIAlertController(title: "Group Invite", message: self.notificationDataSet[indexPath.section][indexPath.row].senderName! + " would like to invite you to group " + self.self.notificationDataSet[indexPath.section][indexPath.row].groupName!, preferredStyle: .alert)
let noteRef = FIRDatabase.database().reference().child("users").child(uid).child("notifications").child(self.notificationDataSet[indexPath.section][indexPath.row].nid!)
let okAction = UIAlertAction(title: "Accept", style: UIAlertActionStyle.default) {
UIAlertAction in
let groupRef = FIRDatabase.database().reference().child("groups").child(self.notificationDataSet[indexPath.section][indexPath.row].gid!).child("members")
let userRef = FIRDatabase.database().reference().child("users").child(uid).child("groups").child(self.notificationDataSet[indexPath.section][indexPath.row].gid!)
groupRef.updateChildValues([uid : self.userName])
userRef.updateChildValues(["gid" : self.notificationDataSet[indexPath.section][indexPath.row].gid!])
userRef.updateChildValues(["groupClass" : self.notificationDataSet[indexPath.section][indexPath.row].className!])
userRef.updateChildValues(["groupName" : self.notificationDataSet[indexPath.section][indexPath.row].groupName!])
userRef.updateChildValues(["groupPictureURL" : self.self.notificationDataSet[indexPath.section][indexPath.row].groupPictureURL!])
noteRef.removeValue()
self.fetchNotifications()
tableView.reloadData()
NSLog("OK Pressed")
}
let cancelAction = UIAlertAction(title: "Decline", style: UIAlertActionStyle.cancel) {
UIAlertAction in
noteRef.removeValue()
self.fetchNotifications()
tableView.reloadData()
NSLog("OK Pressed")
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
| 3121db3bcaf0e62c69999d201dd95592 | 44.023669 | 296 | 0.599619 | false | false | false | false |
AlbertXYZ/HDCP | refs/heads/dev | BarsAroundMe/Pods/RxSwift/RxSwift/Observables/Implementations/ToArray.swift | apache-2.0 | 47 | //
// ToArray.swift
// RxSwift
//
// Created by Junior B. on 20/10/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
final class ToArraySink<SourceType, O: ObserverType> : Sink<O>, ObserverType where O.E == [SourceType] {
typealias Parent = ToArray<SourceType>
let _parent: Parent
var _list = Array<SourceType>()
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceType>) {
switch event {
case .next(let value):
self._list.append(value)
case .error(let e):
forwardOn(.error(e))
self.dispose()
case .completed:
forwardOn(.next(_list))
forwardOn(.completed)
self.dispose()
}
}
}
final class ToArray<SourceType> : Producer<[SourceType]> {
let _source: Observable<SourceType>
init(source: Observable<SourceType>) {
_source = source
}
override func run<O: ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == [SourceType] {
let sink = ToArraySink(parent: self, observer: observer, cancel: cancel)
let subscription = _source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| c34904b4e76e23b1dba5935730fc268c | 28.208333 | 149 | 0.601997 | false | false | false | false |
Mark-SS/LayerPlayer | refs/heads/master | LayerPlayer/CAScrollLayerViewController.swift | mit | 2 | //
// CAScrollLayerViewController.swift
// LayerPlayer
//
// Created by Scott Gardner on 11/10/14.
// Copyright (c) 2014 Scott Gardner. All rights reserved.
//
import UIKit
class CAScrollLayerViewController: UIViewController {
@IBOutlet weak var scrollingView: ScrollingView!
@IBOutlet weak var horizontalScrollingSwitch: UISwitch!
@IBOutlet weak var verticalScrollingSwitch: UISwitch!
var scrollingViewLayer: CAScrollLayer {
return scrollingView.layer as! CAScrollLayer
}
// MARK: - View life cycle
override func viewDidLoad() {
super.viewDidLoad()
scrollingViewLayer.scrollMode = kCAScrollBoth
}
// MARK: - IBActions
@IBAction func panRecognized(sender: UIPanGestureRecognizer) {
var newPoint = scrollingView.bounds.origin
newPoint.x -= sender.translationInView(scrollingView).x
newPoint.y -= sender.translationInView(scrollingView).y
sender.setTranslation(CGPointZero, inView: scrollingView)
scrollingViewLayer.scrollToPoint(newPoint)
if sender.state == .Ended {
UIView.animateWithDuration(0.3, delay: 0, options: .CurveEaseInOut, animations: {
[unowned self] in
self.scrollingViewLayer.scrollToPoint(CGPointZero)
}, completion: nil)
}
}
@IBAction func scrollingSwitchChanged(sender: UISwitch) {
switch (horizontalScrollingSwitch.on, verticalScrollingSwitch.on) {
case (true, true):
scrollingViewLayer.scrollMode = kCAScrollBoth
case (true, false):
scrollingViewLayer.scrollMode = kCAScrollHorizontally
case (false, true):
scrollingViewLayer.scrollMode = kCAScrollVertically
default:
scrollingViewLayer.scrollMode = kCAScrollNone
}
}
}
| 7d07e2f7a589de2c4b9fd98f68e1c44b | 28.62069 | 87 | 0.72468 | false | false | false | false |
shridharmalimca/Shridhar.github.io | refs/heads/master | iOS/Swift 4.0/CustomControls/CustomControls/ViewController.swift | apache-2.0 | 2 | //
// ViewController.swift
// CustomControls
//
// Created by Shridhar Mali on 2/20/18.
// Copyright © 2018 Shridhar Mali. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
@IBDesignable
class DesignableButton: UIButton {
@IBInspectable
public var cornerRedius: CGFloat = 2.0 {
didSet {
self.layer.cornerRadius = self.cornerRedius
}
}
@IBInspectable
public var color: UIColor = UIColor.lightGray {
didSet {
self.backgroundColor = self.color
}
}
@IBInspectable
public var width: CGFloat = 200 {
didSet {
self.frame.size.width = self.width
}
}
@IBInspectable
public var height: CGFloat = 40 {
didSet {
self.frame.size.height = self.height
}
}
}
| cd07c593484c4085766fac4527446c05 | 19.438596 | 80 | 0.6 | false | false | false | false |
mohojojo/iOS-swiftbond-viper | refs/heads/master | Pods/PromiseKit/Extensions/Alamofire/Sources/Alamofire+Promise.swift | mit | 1 | @_exported import Alamofire
import Foundation
#if !COCOAPODS
import PromiseKit
#endif
/**
To import the `Alamofire` category:
use_frameworks!
pod "PromiseKit/Alamofire"
And then in your sources:
import PromiseKit
*/
extension Alamofire.DataRequest {
/// Adds a handler to be called once the request has finished.
public func response() -> Promise<(URLRequest, HTTPURLResponse, Data)> {
return Promise { fulfill, reject in
response(queue: nil) { rsp in
if let error = rsp.error {
reject(error)
} else if let a = rsp.request, let b = rsp.response, let c = rsp.data {
fulfill(a, b, c)
} else {
reject(PMKError.invalidCallingConvention)
}
}
}
}
/// Adds a handler to be called once the request has finished.
public func responseData() -> Promise<Data> {
return Promise { fulfill, reject in
responseData(queue: nil) { response in
switch response.result {
case .success(let value):
fulfill(value)
case .failure(let error):
reject(error)
}
}
}
}
/// Adds a handler to be called once the request has finished.
public func responseString() -> Promise<String> {
return Promise { fulfill, reject in
responseString(queue: nil) { response in
switch response.result {
case .success(let value):
fulfill(value)
case .failure(let error):
reject(error)
}
}
}
}
/// Adds a handler to be called once the request has finished.
public func responseJSON(options: JSONSerialization.ReadingOptions = .allowFragments) -> Promise<Any> {
return Promise { fulfill, reject in
responseJSON(queue: nil, options: options, completionHandler: { response in
switch response.result {
case .success(let value):
fulfill(value)
case .failure(let error):
reject(error)
}
})
}
}
/// Adds a handler to be called once the request has finished. Provides access to the detailed response object.
/// request.responseJSON(with: .response).then { json, response in }
public func responseJSON(with: PMKAlamofireOptions, options: JSONSerialization.ReadingOptions = .allowFragments) -> Promise<(Any, PMKDataResponse)> {
return Promise { fulfill, reject in
responseJSON(queue: nil, options: options, completionHandler: { response in
switch response.result {
case .success(let value):
fulfill(value, PMKDataResponse(response))
case .failure(let error):
reject(error)
}
})
}
}
/// Adds a handler to be called once the request has finished and the resulting JSON is rooted at a dictionary.
public func responseJsonDictionary(options: JSONSerialization.ReadingOptions = .allowFragments) -> Promise<[String: Any]> {
return Promise { fulfill, reject in
responseJSON(queue: nil, options: options, completionHandler: { response in
switch response.result {
case .success(let value):
if let value = value as? [String: Any] {
fulfill(value)
} else {
reject(JSONError.unexpectedRootNode(value))
}
case .failure(let error):
reject(error)
}
})
}
}
/// Adds a handler to be called once the request has finished.
public func responsePropertyList(options: PropertyListSerialization.ReadOptions = PropertyListSerialization.ReadOptions()) -> Promise<Any> {
return Promise { fulfill, reject in
responsePropertyList(queue: nil, options: options) { response in
switch response.result {
case .success(let value):
fulfill(value)
case .failure(let error):
reject(error)
}
}
}
}
}
extension Alamofire.DownloadRequest {
/// Adds a handler to be called once the request has finished.
public func responseData() -> Promise<DownloadResponse<Data>> {
return Promise { fulfill, reject in
responseData(queue: nil) { response in
switch response.result {
case .success:
fulfill(response)
case .failure(let error):
reject(error)
}
}
}
}
}
public enum PMKAlamofireOptions {
case response
}
public struct PMKDataResponse {
fileprivate init(_ rawrsp: Alamofire.DataResponse<Any>) {
request = rawrsp.request
response = rawrsp.response
data = rawrsp.data
timeline = rawrsp.timeline
}
/// The URL request sent to the server.
public let request: URLRequest?
/// The server's response to the URL request.
public let response: HTTPURLResponse?
/// The data returned by the server.
public let data: Data?
/// The timeline of the complete lifecycle of the request.
public let timeline: Timeline
}
| 9d57998f55b145001b267ee06fb51e0c | 32.389222 | 153 | 0.557927 | false | false | false | false |
weizhangCoder/PageViewController_swift | refs/heads/master | ZWPageView/ZWPageView/ZWPageView/ZWPageView.swift | mit | 1 | //
// ZWPageView.swift
// ZWPageView
//
// Created by zhangwei on 16/12/9.
// Copyright © 2016年 jyall. All rights reserved.
//
import UIKit
class ZWPageView: UIView {
//titles 标题文字 childVcs 控制器 parentVc父视图 style设置属性
fileprivate var titles : [String]
fileprivate var childVcs:[UIViewController]
fileprivate var parentVc:UIViewController
fileprivate var style:ZWTitleStyle
fileprivate var titleView:ZWTitleView!
fileprivate var contentView:ZWPageContenView!
init(frame: CGRect,titles:[String],childVcs:[UIViewController],parentVc:UIViewController,style:ZWTitleStyle) {
self.titles = titles
self.childVcs = childVcs
self.parentVc = parentVc
self.style = style
super.init(frame:frame)
parentVc.automaticallyAdjustsScrollViewInsets = false
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MAKE:-创建UI
extension ZWPageView{
fileprivate func setupUI(){
let titleFrame = CGRect(x: 0, y: 0, width: bounds.width, height: style.titleHeigth)
titleView = ZWTitleView(frame: titleFrame, titles: titles, style: style)
titleView.delegate = self
addSubview(titleView)
let contentFrame = CGRect(x: 0, y:style.titleHeigth, width: bounds.width, height: bounds.height - style.titleHeigth)
contentView = ZWPageContenView(frame: contentFrame, childs: childVcs, parent: parentVc)
contentView.delegate = self
addSubview(contentView)
}
}
// MARK:-代理 ZWTitleViewDelagate
extension ZWPageView :ZWTitleViewDelagate{
func titleView(_ titleView: ZWTitleView, targerIndex: Int) {
contentView.setCurrentIndex(targerIndex)
}
}
// MARK:-代理 ZWPageContenViewDelegate
extension ZWPageView : ZWPageContenViewDelegate{
func contentView(_ contentView: ZWPageContenView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
titleView.setTitleWithProgress(sourceIndex: sourceIndex, targerIndex: targetIndex, progress)
}
private func contentViewEndScroll(_ contentView: ZWTitleView) {
titleView.contentViewDidEndScroll()
}
}
| dc8ce10106b03c961a383c12c81cef40 | 26.925926 | 124 | 0.689213 | false | false | false | false |
seanoshea/computer-science-in-swift | refs/heads/master | computer-science-in-swift/InsertionSort.swift | mit | 1 | // Copyright (c) 2015-2016 Sean O'Shea. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
class InsertionSort {
func insertionSort(_ items:inout [Int]) -> [Int] {
for (i, _) in items.enumerated() {
var j:Int = i - 1
let value = items[i]
for _ in stride(from: j, to: -1, by: -1) {
guard j > -1 && items[j] > value else { break }
items[j + 1] = items[j]
j = j - 1
}
items[j + 1] = value
}
return items
}
}
| 3a044383fe67d243d83a65571ca13dfc | 41.342105 | 80 | 0.664388 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Concurrency/async_task_priority.swift | apache-2.0 | 3 | // RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -Xfrontend -disable-availability-checking -parse-as-library -o %t/async_task_priority
// RUN: %target-codesign %t/async_task_priority
// RUN: %target-run %t/async_task_priority
// REQUIRES: VENDOR=apple
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
// UNSUPPORTED: back_deploy_concurrency
import Darwin
@preconcurrency import Dispatch
import StdlibUnittest
func loopUntil(priority: TaskPriority) async {
while (Task.currentPriority != priority) {
await Task.sleep(1_000_000_000)
}
}
func print(_ s: String = "") {
fputs("\(s)\n", stderr)
}
func expectedBasePri(priority: TaskPriority) -> TaskPriority {
let basePri = Task.basePriority!
print("Testing basePri matching expected pri - \(basePri) == \(priority)")
expectEqual(basePri, priority)
return basePri
}
func expectedEscalatedPri(priority: TaskPriority) -> TaskPriority {
let curPri = Task.currentPriority
print("Testing escalated matching expected pri - \(curPri) == \(priority)")
expectEqual(curPri, priority)
return curPri
}
func testNestedTaskPriority(basePri: TaskPriority, curPri: TaskPriority) async {
let _ = expectedBasePri(priority: basePri)
let _ = expectedEscalatedPri(priority: curPri)
}
func childTaskWaitingForEscalation(sem: DispatchSemaphore, basePri: TaskPriority, curPri : TaskPriority) async {
sem.wait() /* Wait to be escalated */
let _ = await testNestedTaskPriority(basePri: basePri, curPri: curPri)
}
@main struct Main {
static func main() async {
let top_level = detach { /* To detach from main actor when running work */
let tests = TestSuite("Task Priority manipulations")
if #available(SwiftStdlib 5.1, *) {
tests.test("Basic escalation test when task is running") {
let parentPri = Task.currentPriority
let sem = DispatchSemaphore(value: 0)
let task = Task(priority: .background) {
let _ = expectedBasePri(priority: .background)
// Wait until task is running before asking to be escalated
sem.signal()
sleep(1)
let _ = expectedEscalatedPri(priority: parentPri)
}
// Wait till child runs and asks to be escalated
sem.wait()
await task.value
}
tests.test("Basic escalation when task is suspended") {
let parentPri = Task.currentPriority
let task = Task(priority: .background) {
await loopUntil(priority: parentPri) /* Suspend task until it is escalated */
let _ = expectedEscalatedPri(priority: parentPri)
}
await task.value // Escalate task BG -> DEF
}
tests.test("Structured concurrency priority propagation") {
let task = Task(priority: .background) {
await loopUntil(priority: .default)
let basePri = expectedBasePri(priority: .background)
let curPri = expectedEscalatedPri(priority: .default)
// Structured concurrency via async let, escalated priority of
// parent should propagate
print("Testing propagation for async let structured concurrency child")
async let child = testNestedTaskPriority(basePri: basePri, curPri: curPri)
await child
let dispatchGroup = DispatchGroup()
// Structured concurrency via task groups, escalated priority should
// propagate
await withTaskGroup(of: Void.self, returning: Void.self) { group in
dispatchGroup.enter()
group.addTask {
print("Testing propagation for task group regular child")
let _ = await testNestedTaskPriority(basePri: basePri, curPri: curPri)
dispatchGroup.leave()
return
}
dispatchGroup.enter()
group.addTask(priority: .utility) {
print("Testing propagation for task group child with specified priority")
let _ = await testNestedTaskPriority(basePri: .utility, curPri: curPri)
dispatchGroup.leave()
return
}
// Wait for child tasks to finish running, don't await since that
// will escalate them
dispatchGroup.wait()
}
}
await task.value // Escalate task BG->DEF
}
tests.test("Unstructured tasks priority propagation") {
let task = Task(priority : .background) {
await loopUntil(priority: .default)
let basePri = expectedBasePri(priority: .background)
let _ = expectedEscalatedPri(priority: .default)
let group = DispatchGroup()
// Create an unstructured task
group.enter()
let _ = Task {
let _ = await testNestedTaskPriority(basePri: basePri, curPri: basePri)
group.leave()
return
}
// Wait for unstructured task to finish running, don't await it
// since that will escalate
group.wait()
}
await task.value // Escalate task BG->DEF
}
tests.test("Task escalation propagation to SC children") {
// Create a task tree and then escalate the parent
let parentPri = Task.currentPriority
let basePri : TaskPriority = .background
let sem = DispatchSemaphore(value: 0)
let sem2 = DispatchSemaphore(value : 0)
let task = Task(priority: basePri) {
async let child = childTaskWaitingForEscalation(sem: sem2, basePri: basePri, curPri: parentPri)
await withTaskGroup(of: Void.self, returning: Void.self) { group in
group.addTask {
let _ = await childTaskWaitingForEscalation(sem: sem2, basePri: basePri, curPri: parentPri)
}
group.addTask(priority: .utility) {
let _ = await childTaskWaitingForEscalation(sem: sem2, basePri: .utility, curPri: parentPri)
}
sem.signal() // Ask for escalation after creating full task tree
sleep(1)
let _ = expectedBasePri(priority: basePri)
let _ = expectedEscalatedPri(priority: parentPri)
sem2.signal() // Ask async let child to evaluate
sem2.signal() // Ask task group child 1 to evaluate
sem2.signal() // Ask task group child 2 to evaluate
}
}
// Wait until children are created and then ask for escalation of
// top level
sem.wait()
await task.value
}
}
await runAllTestsAsync()
}
await top_level.value
}
}
| 5b23e41cdfc5668ebe295c30e6d9a859 | 33.634146 | 116 | 0.59831 | false | true | false | false |
bradwoo8621/Swift-Study | refs/heads/master | Instagram/Instagram/PostViewCell.swift | mit | 1 | //
// PostViewCell.swift
// Instagram
//
// Created by brad.wu on 2017/4/25.
// Copyright © 2017年 bradwoo8621. All rights reserved.
//
import UIKit
class PostViewCell: UITableViewCell {
@IBOutlet weak var avaImg: UIImageView!
@IBOutlet weak var usernameBtn: UIButton!
@IBOutlet weak var dateLbl: UILabel!
@IBOutlet weak var picImg: UIImageView!
@IBOutlet weak var likeBtn: UIButton!
@IBOutlet weak var commentsBtn: UIButton!
@IBOutlet weak var moreBtn: UIButton!
@IBOutlet weak var likeLbl: UILabel!
@IBOutlet weak var titleLbl: UILabel!
@IBOutlet weak var puuidLbl: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
let width = UIScreen.main.bounds.width
avaImg.translatesAutoresizingMaskIntoConstraints = false
usernameBtn.translatesAutoresizingMaskIntoConstraints = false
dateLbl.translatesAutoresizingMaskIntoConstraints = false
picImg.translatesAutoresizingMaskIntoConstraints = false
likeBtn.translatesAutoresizingMaskIntoConstraints = false
commentsBtn.translatesAutoresizingMaskIntoConstraints = false
moreBtn.translatesAutoresizingMaskIntoConstraints = false
likeLbl.translatesAutoresizingMaskIntoConstraints = false
titleLbl.translatesAutoresizingMaskIntoConstraints = false
puuidLbl.translatesAutoresizingMaskIntoConstraints = false
let picWidth = width - 20
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-10-[ava(30)]-10-[pic(\(picWidth))]-5-[like(30)]",
options: [], metrics: nil,
views: ["ava": avaImg, "pic": picImg, "like": likeBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-10-[username]",
options: [], metrics: nil,
views: ["username": usernameBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:[pic]-5-[comment(30)]",
options: [], metrics: nil,
views: ["pic": picImg, "comment": commentsBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:|-15-[date]",
options: [], metrics: nil,
views: ["date": dateLbl]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:[like]-5-[title]-5-|",
options: [], metrics: nil,
views: ["like": likeBtn, "title": titleLbl]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:[pic]-5-[more(30)]",
options: [], metrics: nil,
views: ["pic": picImg, "more": moreBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "V:[pic]-10-[likes]",
options: [], metrics: nil,
views: ["pic": picImg, "likes": likeLbl]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-10-[ava(30)]-10-[username]",
options: [], metrics: nil,
views: ["ava": avaImg, "username": usernameBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-0-[pic]-0-|",
options: [], metrics: nil,
views: ["pic": picImg]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-15-[like(30)]-10-[likes]-20-[comment(30)]",
options: [], metrics: nil,
views: ["like": likeBtn, "likes": likeLbl, "comment": commentsBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:[more(30)]-15-|",
options: [], metrics: nil,
views: ["more": moreBtn]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|-15-[title]-15-|",
options: [], metrics: nil,
views: ["title": titleLbl]))
self.contentView.addConstraints(NSLayoutConstraint.constraints(
withVisualFormat: "H:|[date]-10-|",
options: [], metrics: nil,
views: ["date": dateLbl]))
avaImg.layer.cornerRadius = avaImg.frame.width / 2
avaImg.clipsToBounds = true
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| b14c512bc1eb78c9f62ab1160bfe2cd3 | 37.299065 | 75 | 0.72206 | false | false | false | false |
Havi4/Moya | refs/heads/master | Moya/RxSwift/Moya+RxSwift.swift | mit | 5 | import Foundation
import RxSwift
import Alamofire
/// Subclass of MoyaProvider that returns Observable instances when requests are made. Much better than using completion closures.
public class RxMoyaProvider<T where T: MoyaTarget>: MoyaProvider<T> {
/// Current requests that have not completed or errored yet.
/// Note: Do not access this directly. It is public only for unit-testing purposes (sigh).
public var inflightRequests = Dictionary<Endpoint<T>, Observable<MoyaResponse>>()
/// Initializes a reactive provider.
override public init(endpointClosure: MoyaEndpointsClosure = MoyaProvider.DefaultEndpointMapping, endpointResolver: MoyaEndpointResolution = MoyaProvider.DefaultEndpointResolution, stubBehavior: MoyaStubbedBehavior = MoyaProvider.NoStubbingBehavior, networkActivityClosure: Moya.NetworkActivityClosure? = nil, manager: Manager = Alamofire.Manager.sharedInstance) {
super.init(endpointClosure: endpointClosure, endpointResolver: endpointResolver, stubBehavior: stubBehavior, networkActivityClosure: networkActivityClosure, manager: manager)
}
/// Designated request-making method.
public func request(token: T) -> Observable<MoyaResponse> {
let endpoint = self.endpoint(token)
return defer { [weak self] () -> Observable<MoyaResponse> in
if let weakSelf = self {
objc_sync_enter(weakSelf)
let inFlight = weakSelf.inflightRequests[endpoint]
objc_sync_exit(weakSelf)
if let existingObservable = inFlight {
return existingObservable
}
}
let observable: Observable<MoyaResponse> = create { observer in
let cancellableToken = self?.request(token) { (data, statusCode, response, error) -> () in
if let error = error {
if let statusCode = statusCode {
sendError(observer, NSError(domain: error.domain, code: statusCode, userInfo: error.userInfo))
} else {
sendError(observer, error)
}
} else {
if let data = data {
sendNext(observer, MoyaResponse(statusCode: statusCode!, data: data, response: response))
}
sendCompleted(observer)
}
}
return AnonymousDisposable {
if let weakSelf = self {
objc_sync_enter(weakSelf)
weakSelf.inflightRequests[endpoint] = nil
cancellableToken?.cancel()
objc_sync_exit(weakSelf)
}
}
} >- variable
if let weakSelf = self {
objc_sync_enter(weakSelf)
weakSelf.inflightRequests[endpoint] = observable
objc_sync_exit(weakSelf)
}
return observable
}
}
}
| cd35f25b67b475d65cf180a667b22f64 | 46.523077 | 368 | 0.58854 | false | false | false | false |
MaartenBrijker/project | refs/heads/back | AudioKit/Common/Nodes/Playback/Time Pitch Stretching/AKTimePitch.swift | apache-2.0 | 3 | //
// AKTimePitch.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2015 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// AudioKit version of Apple's TimePitch Audio Unit
///
/// - parameter input: Input node to process
/// - parameter rate: Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
/// - parameter pitch: Pitch (Cents) ranges from -2400 to 2400 (Default: 1.0)
/// - parameter overlap: Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
///
public class AKTimePitch: AKNode, AKToggleable {
private let timePitchAU = AVAudioUnitTimePitch()
/// Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
public var rate: Double = 1.0 {
didSet {
if rate < 0.03125 {
rate = 0.03125
}
if rate > 32.0 {
rate = 32.0
}
timePitchAU.rate = Float(rate)
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return pitch != 0.0 || rate != 1.0
}
/// Pitch (Cents) ranges from -2400 to 2400 (Default: 1.0)
public var pitch: Double = 1.0 {
didSet {
if pitch < -2400 {
pitch = -2400
}
if pitch > 2400 {
pitch = 2400
}
timePitchAU.pitch = Float(pitch)
}
}
/// Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
public var overlap: Double = 8.0 {
didSet {
if overlap < 3.0 {
overlap = 3.0
}
if overlap > 32.0 {
overlap = 32.0
}
timePitchAU.overlap = Float(overlap)
}
}
private var lastKnownRate: Double = 1.0
private var lastKnownPitch: Double = 0.0
/// Initialize the time pitch node
///
/// - parameter input: Input node to process
/// - parameter rate: Rate (rate) ranges from 0.03125 to 32.0 (Default: 1.0)
/// - parameter pitch: Pitch (Cents) ranges from -2400 to 2400 (Default: 1.0)
/// - parameter overlap: Overlap (generic) ranges from 3.0 to 32.0 (Default: 8.0)
///
public init(
_ input: AKNode,
rate: Double = 1.0,
pitch: Double = 0.0,
overlap: Double = 8.0) {
self.rate = rate
self.pitch = pitch
self.overlap = overlap
lastKnownPitch = pitch
lastKnownRate = rate
super.init()
self.avAudioNode = timePitchAU
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
/// Function to start, play, or activate the node, all do the same thing
public func start() {
rate = lastKnownRate
pitch = lastKnownPitch
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
lastKnownPitch = pitch
lastKnownRate = rate
pitch = 0.0
rate = 1.0
}
}
| 6827aa4e60a5f3b3141f711c81179e14 | 27.731481 | 85 | 0.543667 | false | false | false | false |
airspeedswift/swift | refs/heads/master | test/IRGen/objc_class_export.swift | apache-2.0 | 2 | // RUN: %empty-directory(%t)
// RUN: %build-irgen-test-overlays
// RUN: %target-swift-frontend -sdk %S/Inputs -I %t -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// CHECK-DAG: %swift.refcounted = type
// CHECK-DAG: [[HOOZIT:%T17objc_class_export6HoozitC]] = type <{ [[REF:%swift.refcounted]] }>
// CHECK-DAG: [[FOO:%T17objc_class_export3FooC]] = type <{ [[REF]], %TSi }>
// CHECK-DAG: [[INT:%TSi]] = type <{ i64 }>
// CHECK-DAG: [[DOUBLE:%TSd]] = type <{ double }>
// CHECK-DAG: [[NSRECT:%TSo6NSRectV]] = type <{ %TSo7NSPointV, %TSo6NSSizeV }>
// CHECK-DAG: [[NSPOINT:%TSo7NSPointV]] = type <{ %TSd, %TSd }>
// CHECK-DAG: [[NSSIZE:%TSo6NSSizeV]] = type <{ %TSd, %TSd }>
// CHECK: @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" = hidden global %objc_class {
// CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: %objc_class* @"OBJC_METACLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 ptrtoint ({{.*}}* @_METACLASS_DATA__TtC17objc_class_export3Foo to i64)
// CHECK-SAME: }
// CHECK: [[FOO_NAME:@.*]] = private unnamed_addr constant [28 x i8] c"_TtC17objc_class_export3Foo\00"
// CHECK: @_METACLASS_DATA__TtC17objc_class_export3Foo = internal constant {{.*\*}} } {
// CHECK-SAME: i32 129,
// CHECK-SAME: i32 40,
// CHECK-SAME: i32 40,
// CHECK-SAME: i32 0,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK-SAME: @_CLASS_METHODS__TtC17objc_class_export3Foo,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* null
// CHECK-SAME: }, section "__DATA, __objc_const", align 8
// CHECK: @_DATA__TtC17objc_class_export3Foo = internal constant {{.*\*}} } {
// CHECK-SAME: i32 128,
// CHECK-SAME: i32 16,
// CHECK-SAME: i32 24,
// CHECK-SAME: i32 0,
// CHECK-SAME: i8* null,
// CHECK-SAME: i8* getelementptr inbounds ([{{[0-9]+}} x i8], [{{[0-9]+}} x i8]* [[FOO_NAME]], i64 0, i64 0),
// CHECK-SAME: { i32, i32, [6 x { i8*, i8*, i8* }] }* @_INSTANCE_METHODS__TtC17objc_class_export3Foo,
// CHECK-SAME: i8* null,
// CHECK-SAME: @_IVARS__TtC17objc_class_export3Foo,
// CHECK-SAME: i8* null,
// CHECK-SAME: _PROPERTIES__TtC17objc_class_export3Foo
// CHECK-SAME: }, section "__DATA, __objc_const", align 8
// CHECK: @"$s17objc_class_export3FooCMf" = internal global <{{.*}} }> <{
// CHECK-SAME: void ([[FOO]]*)* @"$s17objc_class_export3FooCfD",
// CHECK-SAME: i8** @"$sBOWV",
// CHECK-SAME: i64 ptrtoint (%objc_class* @"OBJC_METACLASS_$__TtC17objc_class_export3Foo" to i64),
// CHECK-SAME: %objc_class* @"OBJC_CLASS_$_{{(_TtCs12_)?}}SwiftObject",
// CHECK-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 add (i64 ptrtoint ({{.*}}* @_DATA__TtC17objc_class_export3Foo to i64), i64 {{1|2}}),
// CHECK-SAME: [[FOO]]* (%swift.type*)* @"$s17objc_class_export3FooC6createACyFZ",
// CHECK-SAME: void (double, double, double, double, [[FOO]]*)* @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"
// CHECK-SAME: }>, section "__DATA,__objc_data, regular"
// -- TODO: The OBJC_CLASS symbol should reflect the qualified runtime name of
// Foo.
// CHECK: @"$s17objc_class_export3FooCN" = hidden alias %swift.type, bitcast (i64* getelementptr inbounds ({{.*}} @"$s17objc_class_export3FooCMf", i32 0, i32 2) to %swift.type*)
// CHECK: @"OBJC_CLASS_$__TtC17objc_class_export3Foo" = hidden alias %swift.type, %swift.type* @"$s17objc_class_export3FooCN"
import gizmo
class Hoozit {}
struct BigStructWithNativeObjects {
var x, y, w : Double
var h : Hoozit
}
@objc class Foo {
@objc var x = 0
@objc class func create() -> Foo {
return Foo()
}
@objc func drawInRect(dirty dirty: NSRect) {
}
// CHECK: define internal void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tFTo"([[OPAQUE:%.*]]* %0, i8* %1, [[NSRECT]]* byval align 8 %2) {{[#0-9]*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE]]* %0 to [[FOO]]*
// CHECK: call swiftcc void @"$s17objc_class_export3FooC10drawInRect5dirtyySo6NSRectV_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
// CHECK: }
@objc func bounds() -> NSRect {
return NSRect(origin: NSPoint(x: 0, y: 0),
size: NSSize(width: 0, height: 0))
}
// CHECK: define internal void @"$s17objc_class_export3FooC6boundsSo6NSRectVyFTo"([[NSRECT]]* noalias nocapture sret %0, [[OPAQUE4:%.*]]* %1, i8* %2) {{[#0-9]*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE4]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC6boundsSo6NSRectVyF"([[FOO]]* swiftself [[CAST]])
@objc func convertRectToBacking(r r: NSRect) -> NSRect {
return r
}
// CHECK: define internal void @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tFTo"([[NSRECT]]* noalias nocapture sret %0, [[OPAQUE5:%.*]]* %1, i8* %2, [[NSRECT]]* byval align 8 %3) {{[#0-9]*}} {
// CHECK: [[CAST:%[a-zA-Z0-9]+]] = bitcast [[OPAQUE5]]* %1 to [[FOO]]*
// CHECK: call swiftcc { double, double, double, double } @"$s17objc_class_export3FooC20convertRectToBacking1rSo6NSRectVAG_tF"(double {{.*}}, double {{.*}}, double {{.*}}, double {{.*}}, [[FOO]]* swiftself [[CAST]])
func doStuffToSwiftSlice(f f: [Int]) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @"$s17objc_class_export3FooC19doStuffToSwiftSlice1fySaySiG_tcAAFTo"
func doStuffToBigSwiftStruct(f f: BigStructWithNativeObjects) {
}
// This function is not representable in Objective-C, so don't emit the objc entry point.
// CHECK-NOT: @_TToFC17objc_class_export3Foo23doStuffToBigSwiftStruct1ffS_FTV17objc_class_export27BigStructWithNativeObjects_T_
@objc init() { }
}
| 5dc4f58d9ec2b6135b4eca048a82a6d8 | 51.258621 | 219 | 0.638073 | false | false | false | false |
ksco/swift-algorithm-club-cn | refs/heads/master | Bit Set/BitSet.playground/Sources/BitSet.swift | mit | 2 | /*
A fixed-size sequence of n bits. Bits have indices 0 to n-1.
*/
public struct BitSet {
/* How many bits this object can hold. */
private(set) public var size: Int
/*
We store the bits in a list of unsigned 64-bit integers.
The first entry, `words[0]`, is the least significant word.
*/
private let N = 64
public typealias Word = UInt64
private(set) public var words: [Word]
private let allOnes = ~Word()
/* Creates a bit set that can hold `size` bits. All bits are initially 0. */
public init(size: Int) {
precondition(size > 0)
self.size = size
// Round up the count to the next multiple of 64.
let n = (size + (N-1)) / N
words = .init(count: n, repeatedValue: 0)
}
/* Converts a bit index into an array index and a mask inside the word. */
private func indexOf(i: Int) -> (Int, Word) {
precondition(i >= 0)
precondition(i < size)
let o = i / N
let m = Word(i - o*N)
return (o, 1 << m)
}
/* Returns a mask that has 1s for all bits that are in the last word. */
private func lastWordMask() -> Word {
let diff = words.count*N - size
if diff > 0 {
// Set the highest bit that's still valid.
let mask = 1 << Word(63 - diff)
// Subtract 1 to turn it into a mask, and add the high bit back in.
return mask | (mask - 1)
} else {
return allOnes
}
}
/*
If the size is not a multiple of N, then we have to clear out the bits
that we're not using, or bitwise operations between two differently sized
BitSets will go wrong.
*/
private mutating func clearUnusedBits() {
words[words.count - 1] &= lastWordMask()
}
/* So you can write bitset[99] = ... */
public subscript(i: Int) -> Bool {
get { return isSet(i) }
set { if newValue { set(i) } else { clear(i) } }
}
/* Sets the bit at the specified index to 1. */
public mutating func set(i: Int) {
let (j, m) = indexOf(i)
words[j] |= m
}
/* Sets all the bits to 1. */
public mutating func setAll() {
for i in 0..<words.count {
words[i] = allOnes
}
clearUnusedBits()
}
/* Sets the bit at the specified index to 0. */
public mutating func clear(i: Int) {
let (j, m) = indexOf(i)
words[j] &= ~m
}
/* Sets all the bits to 0. */
public mutating func clearAll() {
for i in 0..<words.count {
words[i] = 0
}
}
/* Changes 0 into 1 and 1 into 0. Returns the new value of the bit. */
public mutating func flip(i: Int) -> Bool {
let (j, m) = indexOf(i)
words[j] ^= m
return (words[j] & m) != 0
}
/* Determines whether the bit at the specific index is 1 (true) or 0 (false). */
public func isSet(i: Int) -> Bool {
let (j, m) = indexOf(i)
return (words[j] & m) != 0
}
/*
Returns the number of bits that are 1. Time complexity is O(s) where s is
the number of 1-bits.
*/
public var cardinality: Int {
var count = 0
for var x in words {
while x != 0 {
let y = x & ~(x - 1) // find lowest 1-bit
x = x ^ y // and erase it
++count
}
}
return count
}
/* Checks if all the bits are set. */
public func all1() -> Bool {
for i in 0..<words.count - 1 {
if words[i] != allOnes { return false }
}
return words[words.count - 1] == lastWordMask()
}
/* Checks if any of the bits are set. */
public func any1() -> Bool {
for x in words {
if x != 0 { return true }
}
return false
}
/* Checks if none of the bits are set. */
public func all0() -> Bool {
for x in words {
if x != 0 { return false }
}
return true
}
}
// MARK: - Equality
extension BitSet: Equatable {
}
public func ==(lhs: BitSet, rhs: BitSet) -> Bool {
return lhs.words == rhs.words
}
// MARK: - Hashing
extension BitSet: Hashable {
/* Based on the hashing code from Java's BitSet. */
public var hashValue: Int {
var h = Word(1234)
for i in words.count.stride(to: 0, by: -1) {
h ^= words[i - 1] &* Word(i)
}
return Int((h >> 32) ^ h)
}
}
// MARK: - Bitwise operations
extension BitSet: BitwiseOperationsType {
public static var allZeros: BitSet {
return BitSet(size: 64)
}
}
private func copyLargest(lhs: BitSet, _ rhs: BitSet) -> BitSet {
return (lhs.words.count > rhs.words.count) ? lhs : rhs
}
/*
Note: In all of these bitwise operations, lhs and rhs are allowed to have a
different number of bits. The new BitSet always has the larger size.
The extra bits that get added to the smaller BitSet are considered to be 0.
That will strip off the higher bits from the larger BitSet when doing &.
*/
public func &(lhs: BitSet, rhs: BitSet) -> BitSet {
let m = max(lhs.size, rhs.size)
var out = BitSet(size: m)
let n = min(lhs.words.count, rhs.words.count)
for i in 0..<n {
out.words[i] = lhs.words[i] & rhs.words[i]
}
return out
}
public func |(lhs: BitSet, rhs: BitSet) -> BitSet {
var out = copyLargest(lhs, rhs)
let n = min(lhs.words.count, rhs.words.count)
for i in 0..<n {
out.words[i] = lhs.words[i] | rhs.words[i]
}
return out
}
public func ^(lhs: BitSet, rhs: BitSet) -> BitSet {
var out = copyLargest(lhs, rhs)
let n = min(lhs.words.count, rhs.words.count)
for i in 0..<n {
out.words[i] = lhs.words[i] ^ rhs.words[i]
}
return out
}
prefix public func ~(rhs: BitSet) -> BitSet {
var out = BitSet(size: rhs.size)
for i in 0..<rhs.words.count {
out.words[i] = ~rhs.words[i]
}
out.clearUnusedBits()
return out
}
// MARK: - Debugging
extension UInt64 {
/* Writes the bits in little-endian order, LSB first. */
public func bitsToString() -> String {
var s = ""
var n = self
for _ in 1...64 {
s += ((n & 1 == 1) ? "1" : "0")
n >>= 1
}
return s
}
}
extension BitSet: CustomStringConvertible {
public var description: String {
var s = ""
for x in words {
s += x.bitsToString() + " "
}
return s
}
}
| 741cea4e596d5a6840bfc925179ba099 | 23.279352 | 82 | 0.590128 | false | false | false | false |
mattdonnelly/Swifter | refs/heads/master | Sources/SwifterFollowers.swift | mit | 1 | //
// SwifterFollowers.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension Swifter {
/**
GET friendships/no_retweets/ids
Returns a collection of user_ids that the currently authenticated user does not want to receive retweets from. Use POST friendships/update to set the "no retweets" status for a given user account on behalf of the current user.
*/
func listOfNoRetweetsFriends(success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/no_retweets/ids.json"
let parameters = ["stringigy_ids": true]
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in success?(json) }, failure: failure)
}
/**
GET friends/ids
Returns Users (*: user IDs for followees)
Returns a cursored collection of user IDs for every user the specified user is following (otherwise known as their "friends").
At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information.
This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk.
*/
func getUserFollowingIDs(for userTag: UserTag,
cursor: String? = nil,
count: Int? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friends/ids.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["cursor"] ??= cursor
parameters["stringify_ids"] = true
parameters["count"] ??= count
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET followers/ids
Returns a cursored collection of user IDs for every user following the specified user.
At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 5,000 user IDs and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information.
This method is especially powerful when used in conjunction with GET users/lookup, a method that allows you to convert user IDs into full user objects in bulk.
*/
func getUserFollowersIDs(for userTag: UserTag,
cursor: String? = nil,
count: Int? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "followers/ids.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["cursor"] ??= cursor
parameters["stringify_ids"] = true
parameters["count"] ??= count
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET friendships/incoming
Returns a collection of numeric IDs for every user who has a pending request to follow the authenticating user.
*/
func getIncomingPendingFollowRequests(cursor: String? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/incoming.json"
var parameters = [String: Any]()
parameters["cursor"] ??= cursor
parameters["stringify_ids"] = true
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET friendships/outgoing
Returns a collection of numeric IDs for every protected user for whom the authenticating user has a pending follow request.
*/
func getOutgoingPendingFollowRequests(cursor: String? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/outgoing.json"
var parameters = [String: Any]()
parameters["cursor"] ??= cursor
parameters["stringify_ids"] = true
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["ids"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
POST friendships/create
Allows the authenticating users to follow the user specified in the ID parameter.
Returns the befriended user in the requested format when successful. Returns a string describing the failure condition when unsuccessful. If you are already friends with the user a HTTP 403 may be returned, though for performance reasons you may get a 200 OK message even if the friendship already exists.
Actions taken in this method are asynchronous and changes will be eventually consistent.
*/
func followUser(_ userTag: UserTag,
follow: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/create.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["follow"] ??= follow
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST friendships/destroy
Allows the authenticating user to unfollow the user specified in the ID parameter.
Returns the unfollowed user in the requested format when successful. Returns a string describing the failure condition when unsuccessful.
Actions taken in this method are asynchronous and changes will be eventually consistent.
*/
func unfollowUser(_ userTag: UserTag,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/destroy.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
POST friendships/update
Allows one to enable or disable retweets and device notifications from the specified user.
*/
func updateFriendship(with userTag: UserTag,
device: Bool? = nil,
retweets: Bool? = nil,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/update.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["device"] ??= device
parameters["retweets"] ??= retweets
self.postJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET friendships/show
Returns detailed information about the relationship between two arbitrary users.
*/
func showFriendship(between sourceTag: UserTag,
and targetTag: UserTag,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/show.json"
var parameters = [String: Any]()
switch sourceTag {
case .id: parameters["source_id"] = sourceTag.value
case .screenName: parameters["source_screen_name"] = sourceTag.value
}
switch targetTag {
case .id: parameters["target_id"] = targetTag.value
case .screenName: parameters["target_screen_name"] = targetTag.value
}
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
/**
GET friends/list
Returns a cursored collection of user objects for every user the specified user is following (otherwise known as their "friends").
At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information.
*/
func getUserFollowing(for userTag: UserTag,
cursor: String? = nil,
count: Int? = nil,
skipStatus: Bool? = nil,
includeUserEntities: Bool? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friends/list.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["cursor"] ??= cursor
parameters["count"] ??= count
parameters["skip_status"] ??= skipStatus
parameters["include_user_entities"] ??= includeUserEntities
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET followers/list
Returns a cursored collection of user objects for users following the specified user.
At this time, results are ordered with the most recent following first — however, this ordering is subject to unannounced change and eventual consistency issues. Results are given in groups of 20 users and multiple "pages" of results can be navigated through using the next_cursor value in subsequent requests. See Using cursors to navigate collections for more information.
*/
func getUserFollowers(for userTag: UserTag,
cursor: String? = nil,
count: Int? = nil,
skipStatus: Bool? = nil,
includeUserEntities: Bool? = nil,
success: CursorSuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "followers/list.json"
var parameters = [String: Any]()
parameters[userTag.key] = userTag.value
parameters["cursor"] ??= cursor
parameters["count"] ??= count
parameters["skip_status"] ??= skipStatus
parameters["include_user_entities"] ??= includeUserEntities
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json["users"], json["previous_cursor_str"].string, json["next_cursor_str"].string)
}, failure: failure)
}
/**
GET friendships/lookup
Returns the relationships of the authenticating user to the comma-separated list of up to 100 screen_names or user_ids provided. Values for connections can be: following, following_requested, followed_by, none.
*/
func lookupFriendship(with usersTag: UsersTag,
success: SuccessHandler? = nil,
failure: FailureHandler? = nil) {
let path = "friendships/lookup.json"
var parameters = [String: Any]()
parameters[usersTag.key] = usersTag.value
self.getJSON(path: path, baseURL: .api, parameters: parameters, success: { json, _ in
success?(json)
}, failure: failure)
}
}
| c2db2bf1f1bd0dfc2ee0ba0d798620b9 | 44.622951 | 384 | 0.624147 | false | false | false | false |
Syntertainment/SYNUtils | refs/heads/master | SYNUtils/SYNUtils/Extensions/NSString+Utils.swift | mit | 2 | //
// NSString+Utils.swift
// SYNUtils
//
// Created by John Hurliman on 6/23/15.
// Copyright (c) 2015 Syntertainment. All rights reserved.
//
import Foundation
extension String {
struct CharacterSets {
static var uri: NSCharacterSet = {
return NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]\" ").invertedSet
}()
static var whitespaceAndNewline: NSCharacterSet = {
return NSCharacterSet.whitespaceAndNewlineCharacterSet()
}()
}
/// Test if this string starts with a given string.
///
/// :param: prefix String to test against the beginning of the current
/// string
/// :returns: True if this string starts with the given prefix
public func startsWith(prefix: String) -> Bool {
return hasPrefix(prefix)
}
/// Test if this string ends with a given string.
///
/// :param: suffix String to test against the ending of the current string
/// :returns: True if this string ends with the given suffix
public func endsWith(suffix: String) -> Bool {
return hasSuffix(suffix)
}
/// Test if this string contains a given string.
///
/// :param: needle String to search for
/// :returns: True if this string contains the given string
public func contains(needle: String) -> Bool {
return rangeOfString(needle) != nil
}
/// Find all matches in this string for a given regular expression. This
/// method does not support capture groups (use `RegExp#exec()`).
///
/// :param: regex Regular expression to execute against this string
/// :returns: Array of zero or more
public func match(regex: RegExp) -> [String] {
let nsSelf = self as NSString
let matches = regex.matchesInString(self, options: nil, range: fullNSRange()) as! [NSTextCheckingResult]
return matches.map { return nsSelf.substringWithRange($0.range) }
}
/// Returns a new string by replacing all instances of a given substring
/// with another string.
///
/// :param: target Substring to search and replace in this string
/// :param: withString Replacement string
/// :param: options String comparison options
/// :param: range Limit search and replace to a specific range
/// :returns: New string with all instances of `target` replaced by
/// `withString`
public func replace(target: String, withString replacement: String,
options: NSStringCompareOptions = .LiteralSearch,
range searchRange: Range<Int>? = nil) -> String
{
let searchRange: Range<String.Index>? = (searchRange != nil) ? toStringRange(searchRange!) : nil
return stringByReplacingOccurrencesOfString(target, withString: replacement,
options: options, range: searchRange)
}
/// Returns an array containing substrings from this string that have been
/// divided by a given separator.
///
/// :param: separator Separator string to split on. Example: ":"
/// :returns: Array of substrings
public func split(separator: String) -> [String] {
return componentsSeparatedByString(separator)
}
/// Returns an array containing substrings from this string that have been
/// divided by a given set of separator characters.
///
/// :param: separators Separator characters to split on
/// :returns: Array of substrings
public func split(separators: NSCharacterSet) -> [String] {
return componentsSeparatedByCharactersInSet(separators)
}
/// Returns a substring specified by a given character range.
///
/// :param: range Character range to extract
/// :returns: Extracted substring
public func substr(range: Range<Int>) -> String {
return substr(toStringRange(range))
}
/// Returns a substring specified by a given string range.
///
/// :param: range String range to extract
/// :returns: Extracted substring
public func substr(range: Range<String.Index>) -> String {
return substringWithRange(range)
}
/// Returns a substring starting at the specified character offset.
///
/// :param: startIndex Inclusive starting character index
/// :returns: Extracted substring
public func substr(startIndex: Int) -> String {
return substr(startIndex..<self.length)
}
/// Returns a string with leading and trailing whitespace and newlines
/// removed.
///
/// :returns: Trimmed string
public func trim() -> String {
return stringByTrimmingCharactersInSet(CharacterSets.whitespaceAndNewline)
}
/// Returns a string with non-URI-safe characters escaped using percent
/// encoding.
///
/// :returns: Escaped string
public func uriEncoded() -> String {
return stringByAddingPercentEncodingWithAllowedCharacters(CharacterSets.uri)!
}
/// Returns this string's MD5 checksum as a hexidecimal string.
///
/// :returns: 32 character hexadecimal string
public func md5Sum() -> String {
if let data = dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
return MD5(data).calculate().toHexString()
} else {
return "00000000000000000000000000000000"
}
}
// MARK: - Range Helpers
/// Construct a string range by specifying relative offsets from the
/// beginning and end of this string.
///
/// :param: startOffset Relative offset from the beginning of this string.
/// Must be >= 0
/// :param: endOffset Relative offset from the end of this string. Must be
/// <= 0
/// :returns: `Range<String.Index>` for this string
public func rangeWithOffsets(startOffset: Int = 0, endOffset: Int = 0) -> Range<String.Index> {
assert(startOffset >= 0, "Can not create a range extending before startOffset")
assert(endOffset <= 0, "Can not create a range extending beyond endOffset")
return Range<String.Index>(
start: advance(startIndex, startOffset),
end: advance(endIndex, endOffset)
)
}
/// Convert a range specified as character positions to a string range.
///
/// :param: range Character position range. Example: `(0...5)`
/// :returns: `Range<String.Index>` for this string
public func toStringRange(range: Range<Int>) -> Range<String.Index> {
return Range(
start: advance(startIndex, range.startIndex),
end: advance(startIndex, range.endIndex)
)
}
/// Convert an NSRange to a string range.
///
/// :param: NSRange to convert
/// :returns: `Range<String.Index>` for this string
public func toStringRange(range: NSRange) -> Range<String.Index>? {
if let from = String.Index(utf16.startIndex + range.location, within: self),
let to = String.Index(utf16.startIndex + range.location + range.length, within: self)
{
return from ..< to
}
return nil
}
/// Returns an NSRange representing the entire length of this string.
///
/// :returns: `NSRange`
public func fullNSRange() -> NSRange {
return NSMakeRange(0, (self as NSString).length)
}
// MARK: - String Length
/// Returns the character count of this string. More specifically, this
/// counts the number of Unicode grapheme clusters in the string. This is
/// the slowest method for string length but the only accurate method that
/// handles all Unicode characters such as emojis.
public var length: Int {
return count(self)
}
/// Returns the number of UTF8-encoded characters in this string. This is
/// not always equal to the character count, see `length` for more info.
public var utf8Length: Int {
return count(utf8)
}
/// Returns the number of UTF16-encoded characters in this string. This is
/// not always equal to the character count, see `length` for more info.
public var utf16Length: Int {
return count(utf16)
}
// MARK: - Validation
/// Returns true if this string can successfully be parsed as an `NSURL`
/// with non-empty scheme and host.
///
/// :returns: True if this string is a valid URL
public var isValidURL: Bool {
if let candidateURL = NSURL(string: self) {
return candidateURL.scheme != nil && candidateURL.host != nil
}
return false
}
/// Returns true if this string passes a lenient regular expression test for
/// email validation. Note that fully validating an email address according
/// to RFC 2822 and checking for an Internet-routable domain is a
/// non-trivial problem. Therefore, this check errors on the side of
/// leniency, allowing potentially unroutable addresses to pass validation.
///
/// :returns: True if this string looks like a valid email address.
public var isValidEmail: Bool {
let emailRegex = "[A-Z0-9a-z\\._%+-]+@([A-Za-z0-9-]+\\.)+[A-Za-z]{2,4}"
let emailTest = NSPredicate(format: "SELF MATCHES %@", emailRegex)
return emailTest.evaluateWithObject(self)
}
// MARK: - Subscript Access
public subscript(i: Int) -> Character {
return self[advance(startIndex, i)]
}
public subscript(i: Int) -> String {
return String(self[i] as Character)
}
public subscript(r: Range<Int>) -> String {
return substringWithRange(toStringRange(r))
}
}
| 22c43b52b1e597725b61afe2c1b83532 | 36.449612 | 112 | 0.638895 | false | false | false | false |
klaus01/Centipede | refs/heads/master | Centipede/SceneKit/CE_SCNProgram.swift | mit | 1 | //
// CE_SCNProgram.swift
// Centipede
//
// Created by kelei on 2016/9/15.
// Copyright (c) 2016年 kelei. All rights reserved.
//
import SceneKit
extension SCNProgram {
private struct Static { static var AssociationKey: UInt8 = 0 }
private var _delegate: SCNProgram_Delegate? {
get { return objc_getAssociatedObject(self, &Static.AssociationKey) as? SCNProgram_Delegate }
set { objc_setAssociatedObject(self, &Static.AssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
private var ce: SCNProgram_Delegate {
if let obj = _delegate {
return obj
}
if let obj: AnyObject = self.delegate {
if obj is SCNProgram_Delegate {
return obj as! SCNProgram_Delegate
}
}
let obj = getDelegateInstance()
_delegate = obj
return obj
}
private func rebindingDelegate() {
let delegate = ce
self.delegate = nil
self.delegate = delegate
}
internal func getDelegateInstance() -> SCNProgram_Delegate {
return SCNProgram_Delegate()
}
@discardableResult
public func ce_program_handleError(handle: @escaping (SCNProgram, Error) -> Void) -> Self {
ce._program_handleError = handle
rebindingDelegate()
return self
}
}
internal class SCNProgram_Delegate: NSObject, SCNProgramDelegate {
var _program_handleError: ((SCNProgram, Error) -> Void)?
override func responds(to aSelector: Selector!) -> Bool {
let funcDic1: [Selector : Any?] = [
#selector(program(_:handleError:)) : _program_handleError,
]
if let f = funcDic1[aSelector] {
return f != nil
}
return super.responds(to: aSelector)
}
@objc func program(_ program: SCNProgram, handleError error: Error) {
_program_handleError!(program, error)
}
}
| 7eb005b4a5a7ffcef4c4f8da4903970d | 26.342466 | 128 | 0.601202 | false | false | false | false |
byu-oit-appdev/ios-byuSuite | refs/heads/dev | byuSuite/Apps/CougarCash/model/CougarCashPaymentAccount.swift | apache-2.0 | 2 | //
// CougarCashPaymentAccount.swift
// byuSuite
//
// Created by Erik Brady on 12/12/17.
// Copyright © 2017 Brigham Young University. All rights reserved.
//
class CougarCashPaymentAccount: PaymentAccount {
var accountMin: Double!
var accountMax: Double!
init(cougarCashDict: [String: Any]) throws {
try super.init(id: cougarCashDict["id"] as? String,
type: ((cougarCashDict["account_type"] as? String) == "CREDIT_CARD" ? .creditCard : .bankAccount),
number: cougarCashDict["munged_account_num"] as? String,
institution: cougarCashDict["financial_institution"] as? String,
nickname: cougarCashDict["nickname"] as? String,
feeMin: cougarCashDict["min_fee"] as? Double,
feePercent: cougarCashDict["fee_percent"] as? Double)
guard let tempAccountMin = cougarCashDict["minimum"] as? Double,
let tempAccountMax = cougarCashDict["maximum"] as? Double else {
throw InvalidModelError()
}
accountMin = tempAccountMin
accountMax = tempAccountMax
}
}
| b1a5ea3f482885578ab9b053132e2a62 | 30.272727 | 106 | 0.694767 | false | false | false | false |
listen-li/DYZB | refs/heads/master | DYZB/DYZB/Classes/Tools/Extension/UIBarButtonItemExtension.swift | mit | 1 | //
// UIBarButtonItemExtension.swift
// DYZB
//
// Created by admin on 17/7/15.
// Copyright © 2017年 smartFlash. All rights reserved.
//
import UIKit
extension UIBarButtonItem {
/*
class func createItem(imageName : String, highImageName : String, size : CGSize) -> UIBarButtonItem {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
btn.setImage(UIImage(named: highImageName), for: .highlighted)
btn.frame = CGRect(origin: CGPoint.zero, size:size)
return UIBarButtonItem(customView:btn)
}
*/
//便利构造函数:1.convenience开头 2.在构造函数中必须明确调用一个设计的构造函数(self)
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named: imageName), for: .normal)
if highImageName != "" {
btn.setImage(UIImage(named: highImageName), for: .highlighted)
}
if size == CGSize.zero{
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPoint.zero, size:size)
}
self.init(customView:btn)
}
}
| 04db77a1d2d137ca1ce617daaaacff24 | 28.846154 | 105 | 0.612543 | false | false | false | false |
Geor9eLau/WorkHelper | refs/heads/master | Carthage/Checkouts/SwiftCharts/Examples/Examples/NotNumericExample.swift | mit | 1 | //
// NotNumericExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class NotNumericExample: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let quantityVeryLow = MyQuantity(number: 0, text: "Very low")
let quantityLow = MyQuantity(number: 1, text: "low")
let quantityAverage = MyQuantity(number: 2, text: "Average")
let quantityHigh = MyQuantity(number: 3, text: "High")
let quantityVeryHigh = MyQuantity(number: 4, text: "Very high")
let item0 = MyItem(name: "Fruits", quantity: quantityHigh)
let item1 = MyItem(name: "Vegetables", quantity: quantityVeryHigh)
let item2 = MyItem(name: "Fish", quantity: quantityAverage)
let item3 = MyItem(name: "Red meat", quantity: quantityAverage)
let item4 = MyItem(name: "Cereals", quantity: quantityLow)
let chartPoints: [ChartPoint] = [item0, item1, item2, item3, item4].enumerated().map {index, item in
let xLabelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont, rotation: 45, rotationKeep: .top)
let x = ChartAxisValueString(item.name, order: index, labelSettings: xLabelSettings)
let y = ChartAxisValueString(item.quantity.text, order: item.quantity.number, labelSettings: labelSettings)
return ChartPoint(x: x, y: y)
}
let xValues = [ChartAxisValueString("", order: -1)] + chartPoints.map{$0.x} + [ChartAxisValueString("", order: 5)]
func toYValue(_ quantity: MyQuantity) -> ChartAxisValue {
return ChartAxisValueString(quantity.text, order: quantity.number, labelSettings: labelSettings)
}
let yValues = [toYValue(quantityVeryLow), toYValue(quantityLow), toYValue(quantityAverage), toYValue(quantityHigh), toYValue(quantityVeryHigh)]
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: ExamplesDefaults.chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let minBarSpacing: CGFloat = ExamplesDefaults.minBarSpacing + 16
let generator = {(chartPointModel: ChartPointLayerModel, layer: ChartPointsLayer, chart: Chart) -> UIView? in
let bottomLeft = CGPoint(x: layer.innerFrame.origin.x, y: layer.innerFrame.origin.y + layer.innerFrame.height)
let barWidth = layer.minXScreenSpace - minBarSpacing
let (p1, p2): (CGPoint, CGPoint) = (CGPoint(x: chartPointModel.screenLoc.x, y: bottomLeft.y), CGPoint(x: chartPointModel.screenLoc.x, y: chartPointModel.screenLoc.y))
return ChartPointViewBar(p1: p1, p2: p2, width: barWidth, bgColor: UIColor.blue.withAlphaComponent(0.6))
}
let chartPointsLayer = ChartPointsViewsLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, chartPoints: chartPoints, viewGenerator: generator)
let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.black, linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let dividersSettings = ChartDividersLayerSettings(linesColor: UIColor.black, linesWidth: Env.iPad ? 1 : 0.2, start: Env.iPad ? 7 : 3, end: 0, onlyVisibleValues: true)
let dividersLayer = ChartDividersLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: dividersSettings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
dividersLayer,
chartPointsLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
private struct MyQuantity {
let number: Int
let text: String
init(number: Int, text: String) {
self.number = number
self.text = text
}
}
private struct MyItem {
let name: String
let quantity: MyQuantity
init(name: String, quantity: MyQuantity) {
self.name = name
self.quantity = quantity
}
}
| 78e009446c87bdef7d86bff344a8a12f | 43.881818 | 178 | 0.663966 | false | false | false | false |
mibaldi/IOS_MIMO_APP | refs/heads/master | iosAPP/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// iosAPP
//
// Created by mikel balduciel diaz on 31/1/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import UIKit
import CoreData
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var isConected = true
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let notificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge,.Sound], categories: nil)
application.registerUserNotificationSettings(notificationSettings)
return true
}
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
let id = notification.userInfo!["uid"]
let noti = Notification()
noti.notificationId = Int64(id! as! Int)
do{
let notificationSearch = try NotificationsDataHelper.find(noti.notificationId)
if notificationSearch != nil {
try NotificationsDataHelper.delete(noti)
}
} catch _ {
print ("error al borrar notificacion")
}
self.window?.rootViewController?.view.makeToast(notification.alertBody, duration: 4.0, position: .Center, title: nil, image: UIImage(named: "AlarmaActivada"), style: nil, completion: nil)
}
func applicationWillEnterForeground(application: UIApplication) {
do {
let notifications = try NotificationsDataHelper.findAll()! as [Notification]
for noti in notifications {
let noti2 = noti as Notification
let now = NSDate()
if now.compare(noti.firedate) == NSComparisonResult.OrderedDescending || now.compare(noti.firedate) == NSComparisonResult.OrderedSame {
do{
try NotificationsDataHelper.delete(noti2)
} catch _ {
print ("error al borrar notificacion")
}
}
}
}catch _ {
}
}
func applicationWillResignActive(application: UIApplication) {
do{
let notificaciones = try NotificationsDataHelper.findAll()
application.applicationIconBadgeNumber = (notificaciones?.count)!
}catch _ {
print("error al mostrar notificaciones")
}
}
func applicationDidBecomeActive(application: UIApplication) {
AFNetworkReachabilityManager.sharedManager().setReachabilityStatusChangeBlock {
if($0 == .Unknown || $0 == .NotReachable){
self.window?.rootViewController?.view.makeToast(NSLocalizedString("SINCONEXION",comment:"No tienes conexion"), duration: 2, position: .Top)
self.isConected = false
}
if($0 == .ReachableViaWWAN || $0 == .ReachableViaWiFi){
self.isConected = true
}
}
AFNetworkReachabilityManager.sharedManager().startMonitoring()
}
}
| 64e353fa548dc7d354b269bcec0efdb6 | 36.011628 | 195 | 0.628024 | false | false | false | false |
gbammc/Morph | refs/heads/master | Morph/KeyframeAnimation+Effects.swift | mit | 1 | //
// KeyframeAnimation+Effects.swift
// Morph
//
// Created by Alvin on 23/01/2017.
// Copyright © 2017 Alvin. All rights reserved.
//
import UIKit
public extension KeyframeAnimation {
public var easeIn: KeyframeAnimation {
get {
_ = easeInQuad
return self
}
}
public var easeInQuad: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInQuad
return self
}
}
public var easeOutQuad: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutQuad
return self
}
}
public var easeInOutQuad: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutQuad
return self
}
}
public var eaesInCubic: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInCubic
return self
}
}
public var easeOutCubic: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutCubic
return self
}
}
public var easeInOutCubic: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutCubic
return self
}
}
public var easeInQuart: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInQuart
return self
}
}
public var easeOutQuart: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutQuart
return self
}
}
public var easeInOutQuart: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutQuart
return self
}
}
public var easeInQuint: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInQuint
return self
}
}
public var easeOutQuint: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutQuint
return self
}
}
public var easeInOutQuint: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutQuint
return self
}
}
public var easeInSine: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInSine
return self
}
}
public var easeOutSine: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutSine
return self
}
}
public var easeInOutSine: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutSine
return self
}
}
public var easeInExpo: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInExpo
return self
}
}
public var easeOutExpo: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutExpo
return self
}
}
public var easeInOutExpo: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutExpo
return self
}
}
public var easeInCirc: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInCirc
return self
}
}
public var easeOutCirc: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutCubic
return self
}
}
public var easeInOutCirc: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutCirc
return self
}
}
public var easeInElastic: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInElastic
return self
}
}
public var easeOutElastic: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutElastic
return self
}
}
public var easeInOutElastic: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutElastic
return self
}
}
public var easeInBack: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInBack
return self
}
}
public var easeOutBack: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutBack
return self
}
}
public var easeInOutBack: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutBack
return self
}
}
public var easeInBounce: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInBounce
return self
}
}
public var easeOutBounce: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseOutBounce
return self
}
}
public var easeInOutBounce: KeyframeAnimation {
get {
functionBlock = keyframeAnimationFunctionEaseInOutBounce
return self
}
}
}
| 395ecd157fb04b52679bf49a1df626e3 | 23.077922 | 69 | 0.580726 | false | false | false | false |
anishathalye/skipchat | refs/heads/master | SkipChat/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// SkipChat
//
// Created by Katie Siegel on 1/17/15.
// Copyright (c) 2015 SkipChat. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "MIT.SkipChat" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("SkipChat", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SkipChat.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
| efd4776c8bdce9202491093940d11280 | 53.642857 | 290 | 0.714869 | false | false | false | false |
YoungGary/Sina | refs/heads/master | Sina/Sina/Classes/compose发布/TitleView.swift | apache-2.0 | 1 | //
// TitleView.swift
// Sina
//
// Created by YOUNG on 16/9/19.
// Copyright © 2016年 Young. All rights reserved.
//
import UIKit
import SnapKit
class TitleView: UIView {
lazy var titleLabel : UILabel = UILabel()
lazy var screenNameLabel : UILabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TitleView{
private func setupView(){
//add subView
addSubview(titleLabel)
addSubview(screenNameLabel)
//constrains
titleLabel.snp_makeConstraints { (make) in
make.centerX.equalTo(self)
make.bottom.equalTo(self)
}
screenNameLabel.snp_makeConstraints { (make) in
make.centerX.equalTo(self)
make.top.equalTo(self)
}
// 3.设置空间的属性
titleLabel.font = UIFont.systemFontOfSize(16)
screenNameLabel.font = UIFont.systemFontOfSize(14)
screenNameLabel.textColor = UIColor.lightGrayColor()
// 4.设置文字内容
titleLabel.text = "发微博"
screenNameLabel.text = UserAccountViewModel.sharedInstance.account?.screen_name
}
}
| 8fdc15cf95b6cb9d80eb0ddaf62e43da | 19.184615 | 87 | 0.606707 | false | false | false | false |
LawrenceHan/iOS-project-playground | refs/heads/master | Swift_Algorithm/Swift_Algorithm/AdjacencyListGraph.swift | mit | 1 | //
// AdjacencyListGraph.swift
// Swift_Algorithm
//
// Created by Hanguang on 23/11/2016.
// Copyright © 2016 Hanguang. All rights reserved.
//
import Foundation
private class EdgeList<T> where T: Equatable, T: Hashable {
var vertex: Vertex<T>
var edges: [Edge<T>]? = nil
init(vertex: Vertex<T>) {
self.vertex = vertex
}
func addEdge(_ edge: Edge<T>) {
edges?.append(edge)
}
}
open class AdjacencyListGraph<T>: AbstractGraph<T> where T: Equatable, T: Hashable {
fileprivate var adjacencyList: [EdgeList<T>] = []
public required init() {
super.init()
}
public required init(fromGraph graph: AbstractGraph<T>) {
super.init(fromGraph: graph)
}
open override var vertices: [Vertex<T>] {
get {
var vertices = [Vertex<T>]()
for edgeList in adjacencyList {
vertices.append(edgeList.vertex)
}
return vertices
}
}
open override var edges: [Edge<T>] {
get {
var allEdges = Set<Edge<T>>()
for edgeList in adjacencyList {
guard let edges = edgeList.edges else {
continue
}
for edge in edges {
allEdges.insert(edge)
}
}
return Array(allEdges)
}
}
open override func createVertex(_ data: T) -> Vertex<T> {
// check if the vertex already exists
let matchingVertices = vertices.filter { vertex in
return vertex.data == data
}
if matchingVertices.count > 0 {
return matchingVertices.last!
}
// if the vertex doesn't exist, create a new one
let vertex = Vertex(data: data, index: adjacencyList.count)
adjacencyList.append(EdgeList(vertex: vertex))
return vertex
}
open override func addDirectedEdge(_ from: Vertex<T>, to: Vertex<T>, withWeight weight: Double?) {
// works
let edge = Edge(from: from, to: to, weight: weight)
let edgeList = adjacencyList[from.index]
if let _ = edgeList.edges {
edgeList.addEdge(edge)
} else {
edgeList.edges = [edge]
}
}
open override func addUndirectedEdge(_ vertices: (Vertex<T>, Vertex<T>), withWight weight: Double?) {
addDirectedEdge(vertices.0, to: vertices.1, withWeight: weight)
addDirectedEdge(vertices.1, to: vertices.0, withWeight: weight)
}
open override func weightFrom(_ sourceVertex: Vertex<T>, to destinationVertex: Vertex<T>) -> Double? {
guard let edges = adjacencyList[sourceVertex.index].edges else {
return nil
}
for edge: Edge<T> in edges {
if edge.to == destinationVertex {
return edge.weight
}
}
return nil
}
open override func edgessFrom(_ sourceVertex: Vertex<T>) -> [Edge<T>] {
return adjacencyList[sourceVertex.index].edges ?? []
}
open override var description: String {
get {
var rows = [String]()
for edgeList in adjacencyList {
guard let edges = edgeList.edges else {
continue
}
var row = [String]()
for edge in edges {
var value = "\(edge.to.data)"
if edge.weight != nil {
value = "(\(value): \(edge.weight!))"
}
row.append(value)
}
rows.append("\(edgeList.vertex.data) -> [\(row.joined(separator: ", "))]")
}
return rows.joined(separator: "\n")
}
}
}
| 911dd0f9b295c43f2a8a2d0757c16da7 | 28.066667 | 106 | 0.512487 | false | false | false | false |
ray3132138/TestKitchen_1606 | refs/heads/master | TestKitchen/TestKitchen/classes/cookbook/FoodMaterial/model/CBMaterialModel.swift | mit | 1 | //
// CBMaterialModel.swift
// TestKitchen
//
// Created by qianfeng on 16/8/23.
// Copyright © 2016年 ray. All rights reserved.
//
import UIKit
import SwiftyJSON
class CBMaterialModel: NSObject {
var code: String?
var msg: String?
var version: String?
var timestamp: NSNumber?
var data: CBMaterialDataModel?
class func parseModelWithData(data: NSData)->CBMaterialModel{
let jsonData = JSON(data: data)
let model = CBMaterialModel()
model.code = jsonData["code"].string
model.msg = jsonData["msg"].string
model.version = jsonData["version"].string
model.timestamp = jsonData["timestamp"].number
let dataDict = jsonData["data"]
model.data = CBMaterialDataModel.parseModel(dataDict)
return model
}
}
class CBMaterialDataModel: NSObject{
var id: NSNumber?
var name: String?
var text: String?
var data: Array<CBMaterialTypeModel>?
class func parseModel(jsonData: JSON)->CBMaterialDataModel{
let model = CBMaterialDataModel()
model.id = jsonData["id"].number
model.name = jsonData["name"].string
model.text = jsonData["text"].string
var array = Array<CBMaterialTypeModel>()
for (_,subjson) in jsonData["data"] {
let typeModel = CBMaterialTypeModel.parseModel(subjson)
array.append(typeModel)
}
model.data = array
return model
}
}
class CBMaterialTypeModel: NSObject{
var id: String?
var text: String?
var image: String?
var data: Array<CBMaterialSubtypeModel>?
class func parseModel(jsonData: JSON)->CBMaterialTypeModel{
let model = CBMaterialTypeModel()
model.id = jsonData["id"].string
model.text = jsonData["text"].string
model.image = jsonData["image"].string
var array = Array<CBMaterialSubtypeModel>()
for (_,subjson) in jsonData["data"]{
let subtypeModel = CBMaterialSubtypeModel.parseModel(subjson)
array.append(subtypeModel)
}
model.data = array
return model
}
}
class CBMaterialSubtypeModel: NSObject{
var id: String?
var text: String?
var image: String?
class func parseModel(jsonData: JSON)->CBMaterialSubtypeModel{
let model = CBMaterialSubtypeModel()
model.id = jsonData["id"].string
model.text = jsonData["text"].string
model.image = jsonData["image"].string
return model
}
}
| 11acabc839eb734bbbbb5d28525c2ed5 | 20.427481 | 73 | 0.571072 | false | false | false | false |
red3/3DTouchDemo | refs/heads/master | swift/3DTouchDemo/3DTouchDemo/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// 3DTouchDemo
//
// Created by Herui on 15/10/9.
// Copyright © 2015年 harry. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// Saved shortcut item used as a result of an app launch, used later when app is activated.
var launchedShortcutItem: UIApplicationShortcutItem?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
var shouldPerformAdditionalDelegateHandling = true
// If a shortcut was launched, display its information and take the appropriate action
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
launchedShortcutItem = shortcutItem
// This will block "performActionForShortcutItem:completionHandler" from being called.
shouldPerformAdditionalDelegateHandling = false
}
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let main = MainViewController()
window?.rootViewController = UINavigationController(rootViewController: main)
window?.makeKeyAndVisible()
// Install initial versions of our two extra dynamic shortcuts.
if let shortcutItems = application.shortcutItems where shortcutItems.isEmpty {
// Construct the items.
let shortcut2 = UIMutableApplicationShortcutItem(type: "Second", localizedTitle: "Play", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .Play), userInfo:nil)
let shortcut3 = UIMutableApplicationShortcutItem(type: "Third", localizedTitle: "Play", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(type: .Play), userInfo:nil)
let shortcut4 = UIMutableApplicationShortcutItem(type: "Fourth", localizedTitle: "Pause", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "img_share.png"), userInfo:nil)
// Update the application providing the initial 'dynamic' shortcut items.
application.shortcutItems = [shortcut2, shortcut3, shortcut4]
}
return shouldPerformAdditionalDelegateHandling;
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
guard let shortcut = launchedShortcutItem else { return }
handleShortCutItem(shortcut)
launchedShortcutItem = nil
}
/*
Called when the user activates your application by selecting a shortcut on the home screen, except when
application(_:,willFinishLaunchingWithOptions:) or application(_:didFinishLaunchingWithOptions) returns `false`.
You should handle the shortcut in those callbacks and return `false` if possible. In that case, this
callback is used if your application is already launched in the background.
*/
func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: Bool -> Void) {
let handledShortCutItem = handleShortCutItem(shortcutItem)
completionHandler(handledShortCutItem)
}
func handleShortCutItem(item: UIApplicationShortcutItem) ->Bool {
let handled = true;
let navi = self.window!.rootViewController as? UINavigationController
let main = navi!.viewControllers[0] as? MainViewController;
main!.handleTheShortCutItem(item);
return handled;
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 5f94d2cec05edd13bab0e290ded480bf | 51.43 | 285 | 0.728781 | false | false | false | false |
mogstad/Delta | refs/heads/master | sources/extensions/UITableViewDelta.swift | mit | 1 | import UIKit
public extension UITableView {
public typealias TableViewUpdateCallback = (_ from: IndexPath, _ to: IndexPath) -> Void
/// Perform updates on the table view.
///
/// - parameter records: Array of `CollectionRecord` to perform on the
/// table view.
/// - parameter update: An update callback that will be invoked for each
/// update record. It will be invoked with the old and the new index path.
/// Note: due to internals in UITableView’s and UICollecitonView’s we need
/// to query the cell using the old index path, and update the cell with
/// data from the new index path.
public func performUpdates(_ records: [CollectionRecord], update: TableViewUpdateCallback? = nil) {
var changeRecords: [CollectionRecord] = []
self.beginUpdates()
for record in records {
switch record {
case let .addItem(section, index):
let indexPath = IndexPath(row: index, section: section)
self.insertRows(at: [indexPath], with: .automatic)
case let .removeItem(section, index):
let indexPath = IndexPath(row: index, section: section)
self.deleteRows(at: [indexPath], with: .automatic)
case let .moveItem(from, to):
let indexPath = IndexPath(row: to.index, section: to.section)
let fromIndexPath = IndexPath(row: from.index, section: from.section)
self.moveRow(at: fromIndexPath, to: indexPath)
case .changeItem(_, _):
// A Move & Reload for a single cell cannot occur within the same
// update block (Causes a UIKit exception,) so we queue up the
// reloads to occur after all of the insertions
changeRecords.append(record)
case let .reloadSection(section):
self.reloadSections(IndexSet(integer: section), with: .automatic)
case let .moveSection(section, from):
self.moveSection(from, toSection: section)
case let .addSection(section):
self.insertSections(IndexSet(integer: section), with: .automatic)
case let .removeSection(section):
self.deleteSections(IndexSet(integer: section), with: .automatic)
}
}
self.endUpdates()
if changeRecords.count > 0 {
self.beginUpdates()
for record in changeRecords {
guard case let .changeItem(from, to) = record else {
fatalError("changeRecords can contain only .ChangeItem, not \(record)")
}
let indexPath = IndexPath(row: to.index, section: to.section)
let fromIndexPath = IndexPath(row: from.index, section: from.section)
if let updateCallback = update {
updateCallback(fromIndexPath, indexPath)
} else {
self.reloadRows(at: [indexPath], with: .automatic)
}
}
self.endUpdates()
}
}
}
| 580b18d83d90d9c0fcd1b9079e09834f | 40.507463 | 101 | 0.658756 | false | false | false | false |
raymondshadow/SwiftDemo | refs/heads/master | SwiftApp/StudyNote/StudyNote/EventList/SNEventViewController.swift | apache-2.0 | 1 | //
// SNEventViewController.swift
// StudyNote
//
// Created by wuyp on 2019/5/29.
// Copyright © 2019 Raymond. All rights reserved.
//
import UIKit
import Common
class SNEventViewController: UIViewController {
@objc private dynamic let supView = SNEventSupView(frame: CGRect(x: 50, y: 100, width: 200, height: 200))
@objc private dynamic let subView = SNEventSubView(frame: CGRect(x: 20, y: 20, width: 50, height: 50))
@objc private dynamic let supBtn = UIButton(frame: CGRect(x: 50, y: 100, width: 100, height: 100))
@objc private dynamic let subBtn = UIButton(frame: CGRect(x: 20, y: 20, width: 50, height: 50))
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
// self.view.addSubview(supView)
// supView.addSubview(subView)
supView.backgroundColor = UIColor.purple
subView.backgroundColor = UIColor.red
self.view.addSubview(supBtn)
supBtn.addSubview(subBtn)
supBtn.backgroundColor = UIColor.yellow
subBtn.backgroundColor = UIColor.green
subBtn.isEnabled = false
supBtn.addTarget(self, action: #selector(supBtnAction), for: .touchUpInside)
subBtn.addTarget(self, action: #selector(subBtnAction), for: .touchUpInside)
supBtn.setEnlargeArea(areaFloat: 30)
}
@objc private dynamic func supBtnAction() {
print("-----sup btn click")
}
@objc private dynamic func subBtnAction() {
print("======sub btn click")
}
}
| 6915fb9f532468d30d7017bae0e086d7 | 29.705882 | 109 | 0.637931 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.