repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vector-im/vector-ios | Riot/Modules/KeyVerification/Device/SelfVerifyWait/KeyVerificationSelfVerifyWaitViewModel.swift | 1 | 12171 | // File created from ScreenTemplate
// $ createScreen.sh KeyVerification KeyVerificationSelfVerifyWait
/*
Copyright 2020 New Vector Ltd
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
final class KeyVerificationSelfVerifyWaitViewModel: KeyVerificationSelfVerifyWaitViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private let keyVerificationService: KeyVerificationService
private let verificationManager: MXKeyVerificationManager
private let isNewSignIn: Bool
private var secretsRecoveryAvailability: SecretsRecoveryAvailability
private var keyVerificationRequest: MXKeyVerificationRequest?
// MARK: Public
weak var viewDelegate: KeyVerificationSelfVerifyWaitViewModelViewDelegate?
weak var coordinatorDelegate: KeyVerificationSelfVerifyWaitViewModelCoordinatorDelegate?
// MARK: - Setup
init(session: MXSession, isNewSignIn: Bool) {
self.session = session
self.verificationManager = session.crypto.keyVerificationManager
self.keyVerificationService = KeyVerificationService()
self.isNewSignIn = isNewSignIn
self.secretsRecoveryAvailability = session.crypto.recoveryService.vc_availability
}
deinit {
self.unregisterKeyVerificationManagerNewRequestNotification()
}
// MARK: - Public
func process(viewAction: KeyVerificationSelfVerifyWaitViewAction) {
switch viewAction {
case .loadData:
self.loadData()
case .cancel:
self.cancel()
case .recoverSecrets:
switch self.secretsRecoveryAvailability {
case .notAvailable:
fatalError("Should not happen: When recovery is not available button is hidden")
case .available(let secretsRecoveryMode):
self.coordinatorDelegate?.keyVerificationSelfVerifyWaitViewModel(self, wantsToRecoverSecretsWith: secretsRecoveryMode)
}
}
}
// MARK: - Private
private func loadData() {
if !self.isNewSignIn {
MXLog.debug("[KeyVerificationSelfVerifyWaitViewModel] loadData: Send a verification request to all devices")
let keyVerificationService = KeyVerificationService()
self.verificationManager.requestVerificationByToDevice(withUserId: self.session.myUserId, deviceIds: nil, methods: keyVerificationService.supportedKeyVerificationMethods(), success: { [weak self] (keyVerificationRequest) in
guard let self = self else {
return
}
self.keyVerificationRequest = keyVerificationRequest
}, failure: { [weak self] error in
self?.update(viewState: .error(error))
})
continueLoadData()
} else {
// be sure that session has completed its first sync
if session.state >= .running {
// Always send request instead of waiting for an incoming one as per recent EW changes
MXLog.debug("[KeyVerificationSelfVerifyWaitViewModel] loadData: Send a verification request to all devices instead of waiting")
let keyVerificationService = KeyVerificationService()
self.verificationManager.requestVerificationByToDevice(withUserId: self.session.myUserId, deviceIds: nil, methods: keyVerificationService.supportedKeyVerificationMethods(), success: { [weak self] (keyVerificationRequest) in
guard let self = self else {
return
}
self.keyVerificationRequest = keyVerificationRequest
}, failure: { [weak self] error in
self?.update(viewState: .error(error))
})
continueLoadData()
} else {
// show loader
self.update(viewState: .secretsRecoveryCheckingAvailability(VectorL10n.deviceVerificationSelfVerifyWaitRecoverSecretsCheckingAvailability))
NotificationCenter.default.addObserver(self, selector: #selector(sessionStateChanged), name: .mxSessionStateDidChange, object: session)
}
}
}
@objc
private func sessionStateChanged() {
if session.state >= .running {
NotificationCenter.default.removeObserver(self, name: .mxSessionStateDidChange, object: session)
continueLoadData()
}
}
private func continueLoadData() {
// update availability again
self.secretsRecoveryAvailability = session.crypto.recoveryService.vc_availability
let viewData = KeyVerificationSelfVerifyWaitViewData(isNewSignIn: self.isNewSignIn, secretsRecoveryAvailability: self.secretsRecoveryAvailability)
self.registerKeyVerificationManagerNewRequestNotification(for: self.verificationManager)
self.update(viewState: .loaded(viewData))
self.registerTransactionDidStateChangeNotification()
self.registerKeyVerificationRequestChangeNotification()
}
private func cancel() {
self.unregisterKeyVerificationRequestChangeNotification()
self.unregisterKeyVerificationManagerNewRequestNotification()
self.cancelKeyVerificationRequest()
self.coordinatorDelegate?.keyVerificationSelfVerifyWaitViewModelDidCancel(self)
}
private func update(viewState: KeyVerificationSelfVerifyWaitViewState) {
self.viewDelegate?.keyVerificationSelfVerifyWaitViewModel(self, didUpdateViewState: viewState)
}
private func cancelKeyVerificationRequest() {
self.keyVerificationRequest?.cancel(with: MXTransactionCancelCode.user(), success: nil, failure: nil)
}
private func acceptKeyVerificationRequest(_ keyVerificationRequest: MXKeyVerificationRequest) {
keyVerificationRequest.accept(withMethods: self.keyVerificationService.supportedKeyVerificationMethods(), success: { [weak self] in
guard let self = self else {
return
}
self.coordinatorDelegate?.keyVerificationSelfVerifyWaitViewModel(self, didAcceptKeyVerificationRequest: keyVerificationRequest)
}, failure: { [weak self] (error) in
guard let self = self else {
return
}
self.update(viewState: .error(error))
})
}
// MARK: MXKeyVerificationManagerNewRequest
private func registerKeyVerificationManagerNewRequestNotification(for verificationManager: MXKeyVerificationManager) {
NotificationCenter.default.addObserver(self, selector: #selector(keyVerificationManagerNewRequestNotification(notification:)), name: .MXKeyVerificationManagerNewRequest, object: verificationManager)
AppDelegate.theDelegate().handleSelfVerificationRequest = false
}
private func unregisterKeyVerificationManagerNewRequestNotification() {
AppDelegate.theDelegate().handleSelfVerificationRequest = true
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationManagerNewRequest, object: nil)
}
@objc private func keyVerificationManagerNewRequestNotification(notification: Notification) {
guard let userInfo = notification.userInfo, let keyVerificationRequest = userInfo[MXKeyVerificationManagerNotificationRequestKey] as? MXKeyVerificationByToDeviceRequest else {
return
}
guard keyVerificationRequest.isFromMyUser,
keyVerificationRequest.isFromMyDevice == false,
keyVerificationRequest.state == MXKeyVerificationRequestStatePending else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.acceptKeyVerificationRequest(keyVerificationRequest)
}
// MARK: MXKeyVerificationRequestDidChangeNotification
private func registerKeyVerificationRequestChangeNotification() {
NotificationCenter.default.addObserver(self,
selector: #selector(keyVerificationRequestChangeNotification(notification:)),
name: .MXKeyVerificationRequestDidChange,
object: nil)
}
private func unregisterKeyVerificationRequestChangeNotification() {
NotificationCenter.default.removeObserver(self,
name: .MXKeyVerificationRequestDidChange,
object: nil)
}
@objc private func keyVerificationRequestChangeNotification(notification: Notification) {
guard let request = notification.object as? MXKeyVerificationRequest else {
return
}
guard let keyVerificationRequest = keyVerificationRequest,
keyVerificationRequest.requestId == request.requestId else {
return
}
guard keyVerificationRequest.isFromMyUser,
keyVerificationRequest.isFromMyDevice else {
return
}
if keyVerificationRequest.state == MXKeyVerificationRequestStateReady {
self.unregisterKeyVerificationRequestChangeNotification()
self.coordinatorDelegate?.keyVerificationSelfVerifyWaitViewModel(self,
didAcceptKeyVerificationRequest: keyVerificationRequest)
}
}
// MARK: MXKeyVerificationTransactionDidChange
private func registerTransactionDidStateChangeNotification() {
NotificationCenter.default.addObserver(self, selector: #selector(transactionDidStateChange(notification:)), name: .MXKeyVerificationTransactionDidChange, object: nil)
}
private func unregisterTransactionDidStateChangeNotification() {
NotificationCenter.default.removeObserver(self, name: .MXKeyVerificationTransactionDidChange, object: nil)
}
@objc private func transactionDidStateChange(notification: Notification) {
guard let sasTransaction = notification.object as? MXIncomingSASTransaction,
sasTransaction.otherUserId == self.session.myUserId else {
return
}
self.sasTransactionDidStateChange(sasTransaction)
}
private func sasTransactionDidStateChange(_ transaction: MXIncomingSASTransaction) {
switch transaction.state {
case MXSASTransactionStateIncomingShowAccept:
transaction.accept()
case MXSASTransactionStateShowSAS:
self.unregisterTransactionDidStateChangeNotification()
self.coordinatorDelegate?.keyVerificationSelfVerifyWaitViewModel(self, didAcceptIncomingSASTransaction: transaction)
case MXSASTransactionStateCancelled:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelled(reason))
case MXSASTransactionStateCancelledByMe:
guard let reason = transaction.reasonCancelCode else {
return
}
self.unregisterTransactionDidStateChangeNotification()
self.update(viewState: .cancelledByMe(reason))
default:
break
}
}
}
| apache-2.0 | 858171da7af17b8554afa3830afdde36 | 43.258182 | 239 | 0.673486 | 6.543548 | false | false | false | false |
julien-c/swifter | Sources/Swifter/HttpServer.swift | 2 | 4018 | //
// HttpServer.swift
// Swifter
// Copyright (c) 2015 Damian Kołakowski. All rights reserved.
//
import Foundation
#if os(Linux)
import Glibc
import NSLinux
#endif
public class HttpServer {
static let VERSION = "1.0.2"
public typealias Handler = HttpRequest -> HttpResponse
private var router = HttpRouter()
private var listenSocket: Socket = Socket(socketFileDescriptor: -1)
private var clientSockets: Set<Socket> = []
private let clientSocketsLock = NSLock()
public init() { }
public subscript(path: String) -> Handler? {
set {
if let newValue = newValue {
router.register(path, handler: newValue)
}
else {
router.unregister(path)
}
}
get {
return nil
}
}
public var routes: [String] {
return router.routes()
}
public func start(listenPort: in_port_t = 8080) throws {
stop()
listenSocket = try Socket.tcpSocketForListen(listenPort)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
while let socket = try? self.listenSocket.acceptClientSocket() {
HttpServer.lock(self.clientSocketsLock) {
self.clientSockets.insert(socket)
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
let socketAddress = try? socket.peername()
let httpParser = HttpParser()
while let request = try? httpParser.readHttpRequest(socket) {
let keepAlive = httpParser.supportsKeepAlive(request.headers)
let response: HttpResponse
if let (params, handler) = self.router.select(request.url) {
let updatedRequest = HttpRequest(url: request.url, urlParams: request.urlParams, method: request.method, headers: request.headers, body: request.body, address: socketAddress, params: params)
response = handler(updatedRequest)
} else {
response = HttpResponse.NotFound
}
do {
try HttpServer.respond(socket, response: response, keepAlive: keepAlive)
} catch {
print("Failed to send response: \(error)")
break
}
if !keepAlive { break }
}
socket.release()
HttpServer.lock(self.clientSocketsLock) {
self.clientSockets.remove(socket)
}
}
}
self.stop()
}
}
public func stop() {
listenSocket.release()
HttpServer.lock(self.clientSocketsLock) {
for socket in self.clientSockets {
socket.shutdwn()
}
self.clientSockets.removeAll(keepCapacity: true)
}
}
private class func lock(handle: NSLock, closure: () -> ()) {
handle.lock()
closure()
handle.unlock();
}
private class func respond(socket: Socket, response: HttpResponse, keepAlive: Bool) throws {
try socket.writeUTF8("HTTP/1.1 \(response.statusCode()) \(response.reasonPhrase())\r\n")
let length = response.body()?.count ?? 0
try socket.writeUTF8("Content-Length: \(length)\r\n")
if keepAlive {
try socket.writeUTF8("Connection: keep-alive\r\n")
}
for (name, value) in response.headers() {
try socket.writeUTF8("\(name): \(value)\r\n")
}
try socket.writeUTF8("\r\n")
if let body = response.body() {
try socket.writeUInt8(body)
}
}
} | bsd-3-clause | c06037f7d0aef707eff7384fcdecf0df | 33.34188 | 218 | 0.525019 | 4.959259 | false | false | false | false |
rlacaze/LAB-iOS-T9-L210 | LOG210-App-iOS-2.0/aProposController.swift | 1 | 2148 | //
// aProposController.swift
// LOG210-App-iOS-2.0
//
// Created by Romain LACAZE on 2016-03-15.
// Copyright © 2016 Romain LACAZE. All rights reserved.
//
import UIKit
class aProposController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var collectionView: UICollectionView!
let clubs = ["ace", "applets", "aeets"]
let imageArray = [UIImage(named: "ic_ace"), UIImage(named: "ic_applets"), UIImage(named: "ic_aeets")]
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.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.clubs.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
cell.imageView?.image = self.imageArray[indexPath.row]
//cell.titleLabel?.text = self.clubs[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
self.performSegueWithIdentifier("showImage", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showImage"
{
let indexPaths = self.collectionView!.indexPathsForSelectedItems()!
let indexPath = indexPaths[0] as NSIndexPath
let vc = segue.destinationViewController as! aProposDetails
vc.image = self.imageArray[indexPath.row]!
//vc.title = self.clubs[indexPath.row]
}
}
}
| gpl-3.0 | 22d224cf2629b3913f494e454d7265b2 | 29.671429 | 130 | 0.646949 | 5.314356 | false | false | false | false |
WhisperSystems/Signal-iOS | SignalMessaging/Storage Service/StorageServiceManager.swift | 1 | 24454 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc(OWSStorageServiceManager)
class StorageServiceManager: NSObject, StorageServiceManagerProtocol {
@objc
static let shared = StorageServiceManager()
override init() {
super.init()
AppReadiness.runNowOrWhenAppDidBecomeReady {
self.registrationStateDidChange()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.registrationStateDidChange),
name: .RegistrationStateDidChange,
object: nil
)
}
}
@objc private func registrationStateDidChange() {
guard TSAccountManager.sharedInstance().isRegisteredAndReady else { return }
// Schedule a restore. This will do nothing unless we've never
// registered a manifest before.
self.restoreOrCreateManifestIfNecessary()
// If we have any pending changes since we last launch, back them up now.
self.backupPendingChanges()
}
// MARK: -
@objc
func recordPendingDeletions(deletedIds: [AccountId]) {
let operation = StorageServiceOperation.recordPendingDeletions(deletedIds)
StorageServiceOperation.operationQueue.addOperation(operation)
// Schedule a backup to run in the next 10 minutes
// if one hasn't been scheduled already.
scheduleBackupIfNecessary()
}
@objc
func recordPendingDeletions(deletedAddresses: [SignalServiceAddress]) {
let operation = StorageServiceOperation.recordPendingDeletions(deletedAddresses)
StorageServiceOperation.operationQueue.addOperation(operation)
// Schedule a backup to run in the next 10 minutes
// if one hasn't been scheduled already.
scheduleBackupIfNecessary()
}
@objc
func recordPendingUpdates(updatedIds: [AccountId]) {
let operation = StorageServiceOperation.recordPendingUpdates(updatedIds)
StorageServiceOperation.operationQueue.addOperation(operation)
// Schedule a backup to run in the next 10 minutes
// if one hasn't been scheduled already.
scheduleBackupIfNecessary()
}
@objc
func recordPendingUpdates(updatedAddresses: [SignalServiceAddress]) {
let operation = StorageServiceOperation.recordPendingUpdates(updatedAddresses)
StorageServiceOperation.operationQueue.addOperation(operation)
// Schedule a backup to run in the next 10 minutes
// if one hasn't been scheduled already.
scheduleBackupIfNecessary()
}
@objc
func backupPendingChanges() {
let operation = StorageServiceOperation(mode: .backup)
StorageServiceOperation.operationQueue.addOperation(operation)
}
@objc
func restoreOrCreateManifestIfNecessary() {
let operation = StorageServiceOperation(mode: .restoreOrCreate)
StorageServiceOperation.operationQueue.addOperation(operation)
}
// MARK: - Backup Scheduling
private static var scheduledBackupInterval: TimeInterval = kMinuteInterval * 10
private var backupTimer: Timer?
// Schedule a one time backup. By default, this will happen ten
// minutes after the first pending change is recorded.
private func scheduleBackupIfNecessary() {
DispatchQueue.main.async {
// If we already have a backup scheduled, do nothing
guard self.backupTimer == nil else { return }
Logger.info("")
self.backupTimer = Timer.scheduledTimer(
timeInterval: StorageServiceManager.scheduledBackupInterval,
target: self,
selector: #selector(self.backupTimerFired),
userInfo: nil,
repeats: false
)
}
}
@objc func backupTimerFired(_ timer: Timer) {
AssertIsOnMainThread()
Logger.info("")
backupTimer?.invalidate()
backupTimer = nil
backupPendingChanges()
}
}
// MARK: -
@objc(OWSStorageServiceOperation)
class StorageServiceOperation: OWSOperation {
// MARK: - Dependencies
private static var databaseStorage: SDSDatabaseStorage {
return .shared
}
private var databaseStorage: SDSDatabaseStorage {
return .shared
}
static var keyValueStore: SDSKeyValueStore {
return SDSKeyValueStore(collection: "kOWSStorageServiceOperation_IdentifierMap")
}
// MARK: -
// We only ever want to be doing one storage operation at a time.
// Pending updates queued up after a backup operation will not get
// applied until the following backup. This allows us to be certain
// when we do things like resolve conflicts that we're not going to
// blow away any pending updates / deletions.
fileprivate static let operationQueue: OperationQueue = {
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 1
queue.name = logTag()
return queue
}()
fileprivate enum Mode {
case backup
case restoreOrCreate
}
private let mode: Mode
fileprivate init(mode: Mode) {
self.mode = mode
super.init()
self.remainingRetries = 4
}
// MARK: - Run
// Called every retry, this is where the bulk of the operation's work should go.
override public func run() {
Logger.info("\(mode)")
// Do nothing until the feature is enabled.
guard FeatureFlags.socialGraphOnServer else {
return reportSuccess()
}
// We don't have backup keys, do nothing. We'll try a
// fresh restore once the keys are set.
guard KeyBackupService.hasLocalKeys else {
return reportSuccess()
}
switch mode {
case .backup:
backupPendingChanges()
case .restoreOrCreate:
restoreOrCreateManifestIfNecessary()
}
}
// MARK: Mark Pending Changes
fileprivate static func recordPendingUpdates(_ updatedAddresses: [SignalServiceAddress]) -> Operation {
return BlockOperation {
databaseStorage.write { transaction in
let updatedIds = updatedAddresses.map { address in
OWSAccountIdFinder().ensureAccountId(forAddress: address, transaction: transaction)
}
recordPendingUpdates(updatedIds, transaction: transaction)
}
}
}
fileprivate static func recordPendingUpdates(_ updatedIds: [AccountId]) -> Operation {
return BlockOperation {
databaseStorage.write { transaction in
recordPendingUpdates(updatedIds, transaction: transaction)
}
}
}
private static func recordPendingUpdates(_ updatedIds: [AccountId], transaction: SDSAnyWriteTransaction) {
Logger.info("")
var pendingChanges = StorageServiceOperation.accountChangeMap(transaction: transaction)
for accountId in updatedIds {
pendingChanges[accountId] = .updated
}
StorageServiceOperation.setAccountChangeMap(pendingChanges, transaction: transaction)
}
fileprivate static func recordPendingDeletions(_ deletedAddress: [SignalServiceAddress]) -> Operation {
return BlockOperation {
databaseStorage.write { transaction in
let deletedIds = deletedAddress.map { address in
OWSAccountIdFinder().ensureAccountId(forAddress: address, transaction: transaction)
}
recordPendingDeletions(deletedIds, transaction: transaction)
}
}
}
fileprivate static func recordPendingDeletions(_ deletedIds: [AccountId]) -> Operation {
return BlockOperation {
databaseStorage.write { transaction in
recordPendingDeletions(deletedIds, transaction: transaction)
}
}
}
private static func recordPendingDeletions(_ deletedIds: [AccountId], transaction: SDSAnyWriteTransaction) {
Logger.info("")
var pendingChanges = StorageServiceOperation.accountChangeMap(transaction: transaction)
for accountId in deletedIds {
pendingChanges[accountId] = .deleted
}
StorageServiceOperation.setAccountChangeMap(pendingChanges, transaction: transaction)
}
// MARK: Backup
private func backupPendingChanges() {
var pendingChanges: [AccountId: ChangeState] = [:]
var identifierMap: BidirectionalDictionary<AccountId, StorageService.ContactIdentifier> = [:]
var version: UInt64 = 0
var updatedRecords: [StorageServiceProtoContactRecord] = []
databaseStorage.read { transaction in
pendingChanges = StorageServiceOperation.accountChangeMap(transaction: transaction)
identifierMap = StorageServiceOperation.accountToIdentifierMap(transaction: transaction)
version = StorageServiceOperation.manifestVersion(transaction: transaction) ?? 0
// Build an up-to-date contact record for every pending update
updatedRecords =
pendingChanges.lazy.filter { $0.value == .updated }.compactMap { accountId, _ in
do {
guard let contactIdentifier = identifierMap[accountId] else {
// This is a new contact, we need to generate an ID
let contactIdentifier = StorageService.ContactIdentifier.generate()
identifierMap[accountId] = contactIdentifier
let record = try StorageServiceProtoContactRecord.build(
for: accountId,
contactIdentifier: contactIdentifier,
transaction: transaction
)
// Clear pending changes
pendingChanges[accountId] = nil
return record
}
let record = try StorageServiceProtoContactRecord.build(
for: accountId,
contactIdentifier: contactIdentifier,
transaction: transaction
)
// Clear pending changes
pendingChanges[accountId] = nil
return record
} catch {
owsFailDebug("Unexpectedly failed to process changes for account \(error)")
// If for some reason we failed, we'll just skip it and try this account again next backup.
return nil
}
}
}
// Lookup the contact identifier for every pending deletion
let deletedIdentifiers: [StorageService.ContactIdentifier] =
pendingChanges.lazy.filter { $0.value == .deleted }.compactMap { accountId, _ in
// Clear the pending change
pendingChanges[accountId] = nil
guard let contactIdentifier = identifierMap[accountId] else {
// This contact doesn't exist in our records, it may have been
// added and then deleted before a backup occured. We can safely skip it.
return nil
}
// Remove this contact from the mapping
identifierMap[accountId] = nil
return contactIdentifier
}
// If we have no pending changes, we have nothing left to do
guard !deletedIdentifiers.isEmpty || !updatedRecords.isEmpty else {
return reportSuccess()
}
// Bump the manifest version
version += 1
let manifestBuilder = StorageServiceProtoManifestRecord.builder(version: version)
manifestBuilder.setKeys(identifierMap.map { $1.data })
let manifest: StorageServiceProtoManifestRecord
do {
manifest = try manifestBuilder.build()
} catch {
return reportError(OWSAssertionError("failed to build proto"))
}
StorageService.updateManifest(
manifest,
newContacts: updatedRecords,
deletedContacts: deletedIdentifiers
).done(on: .global()) { conflictingManifest in
guard let conflictingManifest = conflictingManifest else {
// Successfuly updated, store our changes.
self.databaseStorage.write { transaction in
StorageServiceOperation.setConsecutiveConflicts(0, transaction: transaction)
StorageServiceOperation.setAccountChangeMap(pendingChanges, transaction: transaction)
StorageServiceOperation.setManifestVersion(version, transaction: transaction)
StorageServiceOperation.setAccountToIdentifierMap(identifierMap, transaction: transaction)
}
return self.reportSuccess()
}
// Throw away all our work, resolve conflicts, and try again.
self.mergeLocalManifest(withRemoteManifest: conflictingManifest, backupAfterSuccess: true)
}.catch { error in
self.reportError(withUndefinedRetry: error)
}.retainUntilComplete()
}
// MARK: Restore
private func restoreOrCreateManifestIfNecessary() {
var manifestVersion: UInt64?
databaseStorage.read { transaction in
manifestVersion = StorageServiceOperation.manifestVersion(transaction: transaction)
}
StorageService.fetchManifest().done(on: .global()) { manifest in
guard let manifest = manifest else {
// There is no existing manifest, lets create one with all our contacts.
return self.createNewManifest(version: 1)
}
guard manifest.version != manifestVersion else {
// Our manifest version matches the server version, nothing to do here.
return self.reportSuccess()
}
// Our manifest is not the latest, merge in the latest copy.
self.mergeLocalManifest(withRemoteManifest: manifest, backupAfterSuccess: false)
}.catch { error in
if let storageError = error as? StorageService.StorageError {
// If we succeeded to fetch the manifest but were unable to decrypt it,
// it likely means our keys changed. Create a new manifest with the
// latest version of our backup key.
if case .decryptionFailed(let previousManifestVersion) = storageError {
return self.createNewManifest(version: previousManifestVersion + 1)
}
return self.reportError(storageError)
}
self.reportError(OWSAssertionError("received unexpected error when fetching manifest"))
}.retainUntilComplete()
}
private func createNewManifest(version: UInt64) {
var allContactRecords: [StorageServiceProtoContactRecord] = []
var identifierMap: BidirectionalDictionary<AccountId, StorageService.ContactIdentifier> = [:]
databaseStorage.read { transaction in
SignalRecipient.anyEnumerate(transaction: transaction) { recipient, _ in
if recipient.devices.count > 0 {
let contactIdentifier = StorageService.ContactIdentifier.generate()
identifierMap[recipient.accountId] = contactIdentifier
do {
allContactRecords.append(
try StorageServiceProtoContactRecord.build(
for: recipient.accountId,
contactIdentifier: contactIdentifier,
transaction: transaction
)
)
} catch {
// We'll just skip it, something may be wrong with our local data.
// We'll try and backup this contact again when something changes.
owsFailDebug("unexpectedly failed to build contact record")
}
}
}
}
let manifestBuilder = StorageServiceProtoManifestRecord.builder(version: version)
manifestBuilder.setKeys(allContactRecords.map { $0.key })
let manifest: StorageServiceProtoManifestRecord
do {
manifest = try manifestBuilder.build()
} catch {
return reportError(OWSAssertionError("failed to build proto"))
}
StorageService.updateManifest(
manifest,
newContacts: allContactRecords,
deletedContacts: []
).done(on: .global()) { conflictingManifest in
guard let conflictingManifest = conflictingManifest else {
// Successfuly updated, store our changes.
self.databaseStorage.write { transaction in
StorageServiceOperation.setConsecutiveConflicts(0, transaction: transaction)
StorageServiceOperation.setAccountChangeMap([:], transaction: transaction)
StorageServiceOperation.setManifestVersion(version, transaction: transaction)
StorageServiceOperation.setAccountToIdentifierMap(identifierMap, transaction: transaction)
}
return self.reportSuccess()
}
// We got a conflicting manifest that we were able to decrypt, so we may not need
// to recreate our manifest after all. Throw away all our work, resolve conflicts,
// and try again.
self.mergeLocalManifest(withRemoteManifest: conflictingManifest, backupAfterSuccess: true)
}.catch { error in
self.reportError(withUndefinedRetry: error)
}.retainUntilComplete()
}
// MARK: - Conflict Resolution
private func mergeLocalManifest(withRemoteManifest manifest: StorageServiceProtoManifestRecord, backupAfterSuccess: Bool) {
var identifierMap: BidirectionalDictionary<AccountId, StorageService.ContactIdentifier> = [:]
var pendingChanges: [AccountId: ChangeState] = [:]
var consecutiveConflicts = 0
databaseStorage.write { transaction in
identifierMap = StorageServiceOperation.accountToIdentifierMap(transaction: transaction)
pendingChanges = StorageServiceOperation.accountChangeMap(transaction: transaction)
// Increment our conflict count.
consecutiveConflicts = StorageServiceOperation.consecutiveConflicts(transaction: transaction)
consecutiveConflicts += 1
StorageServiceOperation.setConsecutiveConflicts(consecutiveConflicts, transaction: transaction)
}
// If we've tried many times in a row to resolve conflicts, something weird is happening
// (potentially a bug on the service or a race with another app). Give up and wait until
// the next backup runs.
guard consecutiveConflicts <= StorageServiceOperation.maxConsecutiveConflicts else {
owsFailDebug("unexpectedly have had numerous repeated conflicts")
// Clear out the consecutive conflicts count so we can try again later.
databaseStorage.write { transaction in
StorageServiceOperation.setConsecutiveConflicts(0, transaction: transaction)
}
return reportError(OWSAssertionError("exceeded max consectuive conflicts, creating a new manifest"))
}
// Fetch all the contacts in the new manifest and resolve any conflicts appropriately.
StorageService.fetchContacts(for: manifest.keys.map { .init(data: $0) }).done(on: .global()) { contacts in
self.databaseStorage.write { transaction in
for contact in contacts {
switch contact.mergeWithLocalContact(transaction: transaction) {
case .invalid:
// This contact record was invalid, ignore it.
// we'll clear it out in the next backup.
break
case .needsUpdate(let accountId):
// our local version was newer, flag this account as needing a sync
pendingChanges[accountId] = .updated
case .resolved(let accountId):
// update the mapping, this could be a new account
identifierMap[accountId] = contact.contactIdentifier
}
}
StorageServiceOperation.setConsecutiveConflicts(0, transaction: transaction)
StorageServiceOperation.setAccountChangeMap(pendingChanges, transaction: transaction)
StorageServiceOperation.setManifestVersion(manifest.version, transaction: transaction)
StorageServiceOperation.setAccountToIdentifierMap(identifierMap, transaction: transaction)
if backupAfterSuccess { StorageServiceManager.shared.backupPendingChanges() }
self.reportSuccess()
}
}.catch { error in
if let storageError = error as? StorageService.StorageError {
return self.reportError(storageError)
}
self.reportError(OWSAssertionError("received unexpected error when fetching contacts"))
}.retainUntilComplete()
}
// MARK: - Accessors
private static let accountToIdentifierMapKey = "accountToIdentifierMap"
private static let accountChangeMapKey = "accountChangeMap"
private static let manifestVersionKey = "manifestVersion"
private static let consecutiveConflictsKey = "consecutiveConflicts"
private static func manifestVersion(transaction: SDSAnyReadTransaction) -> UInt64? {
return keyValueStore.getUInt64(manifestVersionKey, transaction: transaction)
}
private static func setManifestVersion( _ verison: UInt64, transaction: SDSAnyWriteTransaction) {
keyValueStore.setUInt64(verison, key: manifestVersionKey, transaction: transaction)
}
private static func accountToIdentifierMap(transaction: SDSAnyReadTransaction) -> BidirectionalDictionary<AccountId, StorageService.ContactIdentifier> {
guard let anyDictionary = keyValueStore.getObject(accountToIdentifierMapKey, transaction: transaction) as? AnyBidirectionalDictionary,
let dictionary = BidirectionalDictionary<AccountId, Data>(anyDictionary) else {
return [:]
}
return dictionary.mapValues { .init(data: $0) }
}
private static func setAccountToIdentifierMap( _ dictionary: BidirectionalDictionary<AccountId, StorageService.ContactIdentifier>, transaction: SDSAnyWriteTransaction) {
keyValueStore.setObject(
AnyBidirectionalDictionary(dictionary.mapValues { $0.data }),
key: accountToIdentifierMapKey,
transaction: transaction
)
}
private enum ChangeState: Int {
case unchanged = 0
case updated = 1
case deleted = 2
}
private static func accountChangeMap(transaction: SDSAnyReadTransaction) -> [AccountId: ChangeState] {
let accountIdToIdentifierData = keyValueStore.getObject(accountChangeMapKey, transaction: transaction) as? [AccountId: Int] ?? [:]
return accountIdToIdentifierData.compactMapValues { ChangeState(rawValue: $0) }
}
private static func setAccountChangeMap(_ map: [AccountId: ChangeState], transaction: SDSAnyWriteTransaction) {
keyValueStore.setObject(map.mapValues { $0.rawValue }, key: accountChangeMapKey, transaction: transaction)
}
private static var maxConsecutiveConflicts = 3
private static func consecutiveConflicts(transaction: SDSAnyReadTransaction) -> Int {
return keyValueStore.getInt(consecutiveConflictsKey, transaction: transaction) ?? 0
}
private static func setConsecutiveConflicts( _ consecutiveConflicts: Int, transaction: SDSAnyWriteTransaction) {
keyValueStore.setInt(consecutiveConflicts, key: consecutiveConflictsKey, transaction: transaction)
}
}
| gpl-3.0 | 039146f51d9560ef1b018e3268a5ddf8 | 39.621262 | 173 | 0.638587 | 5.902486 | false | false | false | false |
nmdias/FeedKit | Sources/FeedKit/Models/RSS/RSSFeedCloud.swift | 2 | 4753 | //
// RSSFeedCloud.swift
//
// Copyright (c) 2016 - 2018 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
/// Allows processes to register with a cloud to be notified of updates to
/// the channel, implementing a lightweight publish-subscribe protocol for
/// RSS feeds.
///
/// Example: <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="pingMe" protocol="soap"/>
///
/// <cloud> is an optional sub-element of <channel>.
///
/// It specifies a web service that supports the rssCloud interface which can
/// be implemented in HTTP-POST, XML-RPC or SOAP 1.1.
///
/// Its purpose is to allow processes to register with a cloud to be notified
/// of updates to the channel, implementing a lightweight publish-subscribe
/// protocol for RSS feeds.
///
/// <cloud domain="rpc.sys.com" port="80" path="/RPC2" registerProcedure="myCloud.rssPleaseNotify" protocol="xml-rpc" />
///
/// In this example, to request notification on the channel it appears in,
/// you would send an XML-RPC message to rpc.sys.com on port 80, with a path
/// of /RPC2. The procedure to call is myCloud.rssPleaseNotify.
///
/// A full explanation of this element and the rssCloud interface is here:
/// http://cyber.law.harvard.edu/rss/soapMeetsRss.html#rsscloudInterface
public class RSSFeedCloud {
/// The attributes of the `<channel>`'s `<cloud>` element.
public class Attributes {
/// The domain to register notification to.
public var domain: String?
/// The port to connect to.
public var port: Int?
/// The path to the RPC service. e.g. "/RPC2".
public var path: String?
/// The procedure to call. e.g. "myCloud.rssPleaseNotify" .
public var registerProcedure: String?
/// The `protocol` specification. Can be HTTP-POST, XML-RPC or SOAP 1.1 -
/// Note: "protocol" is a reserved keyword, so `protocolSpecification`
/// is used instead and refers to the `protocol` attribute of the `cloud`
/// element.
public var protocolSpecification: String?
}
/// The element's attributes.
public var attributes: Attributes?
public init() { }
}
// MARK: - Initializers
extension RSSFeedCloud {
convenience init(attributes attributeDict: [String : String]) {
self.init()
self.attributes = RSSFeedCloud.Attributes(attributes: attributeDict)
}
}
extension RSSFeedCloud.Attributes {
convenience init?(attributes attributeDict: [String : String]) {
if attributeDict.isEmpty {
return nil
}
self.init()
self.domain = attributeDict["domain"]
self.port = Int(attributeDict["port"] ?? "")
self.path = attributeDict["path"]
self.registerProcedure = attributeDict["registerProcedure"]
self.protocolSpecification = attributeDict["protocol"]
}
}
// MARK: - Equatable
extension RSSFeedCloud: Equatable {
public static func ==(lhs: RSSFeedCloud, rhs: RSSFeedCloud) -> Bool {
return lhs.attributes == rhs.attributes
}
}
extension RSSFeedCloud.Attributes: Equatable {
public static func ==(lhs: RSSFeedCloud.Attributes, rhs: RSSFeedCloud.Attributes) -> Bool {
return
lhs.domain == rhs.domain &&
lhs.port == rhs.port &&
lhs.path == rhs.path &&
lhs.registerProcedure == rhs.registerProcedure &&
lhs.protocolSpecification == rhs.protocolSpecification
}
}
| mit | 90834470a65ff8f6b9d215f9ee3bb80d | 34.470149 | 120 | 0.654744 | 4.425512 | false | false | false | false |
OpenTimeApp/OpenTimeIOSSDK | OpenTimeSDK/Classes/OTPhoneHelper.swift | 1 | 4723 | //
// OTPhoneHelper.swift
// OpenTimeSDK
//
// Created by Josh Woodcock on 10/25/15.
// Copyright © 2015 Connecting Open Time, LLC. All rights reserved.
//
import Foundation
import libPhoneNumber_iOS
public class OTPhoneHelper {
private static let _phoneUtil = NBPhoneNumberUtil();
private static func _getCountry() -> String {
let countryCode: String = (Locale.current as NSLocale).object(forKey: NSLocale.Key.countryCode) as! String
return countryCode;
}
/**
Formats the phone with the OpenTime standard international phone format +### ### #########
If the phone number is not a valid phone number the phone will not be formatted.
- returns: A formatted phone for valid phone numbers.
*/
public static func format(phone: String) -> String
{
if(phone == "") {
return "";
}
let country = self._getCountry();
if(self._phoneUtil.isViablePhoneNumber(phone)) {
var error: NSError? = nil;
var number: NBPhoneNumber!
do {
number = try _phoneUtil.parse(phone, defaultRegion: country)
} catch let error1 as NSError {
error = error1
number = nil
};
if(error != nil || number == nil) {
return "";
}
var defaultFormatted: String!
do {
defaultFormatted = try _phoneUtil.format(number, numberFormat: NBEPhoneNumberFormat.INTERNATIONAL)
} catch let error1 as NSError {
error = error1
defaultFormatted = nil
};
if(error != nil || defaultFormatted == nil || defaultFormatted == "") {
return "";
}
if((defaultFormatted as NSString).range(of: "-").location == NSNotFound) {
return defaultFormatted;
}
var formatted = self._replaceFirst(find: "-", replaceWith: " ", subject: defaultFormatted);
if((defaultFormatted as NSString).range(of: "-").location == NSNotFound) {
return formatted;
}
formatted = self._replace(find: "-", replaceWith: "", subject: formatted);
number = nil;
return formatted;
}else{
return phone;
}
}
public static func isSearchable(phone: String) -> Bool {
let isSearchable = self._phoneUtil.isViablePhoneNumber(phone);
return isSearchable;
}
public static func getDialable(phoneNumber: String) -> String {
let badChars = CharacterSet(charactersIn: "0123456789-+()");
let goodChars = badChars.inverted;
let expandPhone = phoneNumber.components(separatedBy: goodChars);
let cleanPhone = expandPhone.joined(separator: "");
return cleanPhone;
}
private static func _replaceFirst(find: String, replaceWith: Character, subject: String) -> String {
if(subject != "") {
var explode = subject.components(separatedBy: find);
var joined = "";
if(explode.count >= 2) {
joined = explode[0] + String(replaceWith) + explode[1];
for i in 2..<explode.count {
joined += explode[i];
}
return joined;
}else{
return subject;
}
}else{
return "";
}
}
private static func _replace(find: String, replaceWith: String, subject: String)->String
{
let myDictionary = [find:replaceWith];
var newString = subject;
for (originalWord, newWord) in myDictionary {
newString = newString.replacingOccurrences(of: originalWord, with:newWord, options: NSString.CompareOptions.literal, range: nil)
}
return newString;
}
public static func isValid(phone: String) -> Bool {
if(self._phoneUtil.isViablePhoneNumber(phone)) {
let country = self._getCountry();
var number: NBPhoneNumber!
number = try! self._phoneUtil.parse(phone, defaultRegion: country);
if(self._phoneUtil.isValidNumber(forRegion: number, regionCode: country)) {
number = nil;
return true;
}else{
number = nil;
return false;
}
}else{
return false;
}
}
}
| mit | 0a2801935f46586856d419d3728b3e99 | 31.122449 | 140 | 0.52626 | 5.160656 | false | false | false | false |
amandafer/ecommerce | ecommerce/View/TabBarContView.swift | 1 | 1172 | //
// TabBarContView.swift
// ecommerce
//
// Created by Amanda Fernandes on 15/04/2017.
// Copyright © 2017 Amanda Fernandes. All rights reserved.
//
import UIKit
@IBDesignable
class ColourTab: UITabBarController {
@IBInspectable var barBgColor: UIColor? {
didSet {
self.tabBar.barTintColor = barBgColor
self.tabBar.isTranslucent = false
}
}
@IBInspectable var textColor: UIColor? {
didSet {
//self.tabBar.tintColor = textColor
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: textColor!], for: .normal)
}
}
@IBInspectable var selectedTextColor: UIColor? {
didSet {
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: selectedTextColor!], for: .selected)
}
}
}
extension UITabBar {
// Changes the height of the Tab Bar
override open func sizeThatFits(_ size: CGSize) -> CGSize {
super.sizeThatFits(size)
var sizeThatFits = super.sizeThatFits(size)
sizeThatFits.height = 58 // wanted height
return sizeThatFits
}
}
| mit | 638a30b487aa3b7e7a2a3b5ebb22aecf | 26.880952 | 130 | 0.650726 | 5.091304 | false | false | false | false |
gtranchedone/NFYU | NFYUTests/MocksAndStubs/FakeLocationManager.swift | 1 | 1842 | //
// FakeLocationManager.swift
// NFYU
//
// Created by Gianluca Tranchedone on 02/11/2015.
// Copyright © 2015 Gianluca Tranchedone. All rights reserved.
//
import Foundation
import CoreLocation
@testable import NFYU
class FakeUserLocationManager: UserLocationManager {
private(set) var didRequestPermissions = false
private(set) var didRequestCurrentLocation = false
var allowUseOfLocationServices = false
var shouldCallCompletionBlock = true
var stubDidRequestPermissions = true
var stubResult: UserLocationManagerResult?
var locationServicesEnabled: Bool {
return allowUseOfLocationServices
}
var didRequestAuthorization: Bool {
return didRequestPermissions
}
@discardableResult func requestUserAuthorizationForUsingLocationServices(_ completionBlock: @escaping () -> ()) -> Bool {
didRequestPermissions = stubDidRequestPermissions
completionBlock()
return stubDidRequestPermissions
}
@discardableResult func requestCurrentLocation(_ completionBlock: @escaping (UserLocationManagerResult) -> ()) {
didRequestCurrentLocation = true
if let stubResult = stubResult, shouldCallCompletionBlock {
completionBlock(stubResult)
}
}
}
class FakeLocationManager: CLLocationManager {
static var stubAuthorizationStatus: CLAuthorizationStatus = .notDetermined
var didRequestAuthorizationForInUse = false
var didRequestLocation = false
override class func authorizationStatus() -> CLAuthorizationStatus {
return stubAuthorizationStatus
}
override func requestLocation() {
didRequestLocation = true
}
override func requestWhenInUseAuthorization() {
didRequestAuthorizationForInUse = true
}
}
| mit | 04749358f14c989a8b654fd879c6fda7 | 27.765625 | 125 | 0.715372 | 6.075908 | false | false | false | false |
LoganHollins/SuperStudent | SuperStudent/Question.swift | 1 | 752 | //
// Question.swift
// SuperStudent
//
// Created by Tom Bui on 2015-11-27.
// Copyright © 2015 Logan Hollins. All rights reserved.
//
import Foundation
class Question {
var id = ""
var title = ""
var question = ""
var category = ""
var date = ""
var time = ""
var postedBy = ""
var upvotes = ""
init (id: String, title: String, question: String, category : String, date: String, time: String, postedBy: String, upvotes: String) {
self.id = id
self.title = title
self.question = question
self.category = category
self.date = date
self.time = time
self.postedBy = postedBy
self.upvotes = upvotes
}
init(){
}
} | gpl-2.0 | 530b52d5d4b3b35d24402e8a0a89895f | 19.888889 | 138 | 0.55526 | 3.851282 | false | false | false | false |
johnno1962d/swift | test/SourceKit/DocSupport/Inputs/main.swift | 3 | 1992 | var globV: Int
class CC0 {
var x: Int = 0
}
class CC {
var instV: CC0
func meth() {}
func instanceFunc0(_ a: Int, b: Float) -> Int {
return 0
}
func instanceFunc1(a x: Int, b y: Float) -> Int {
return 0
}
class func smeth() {}
init() {
instV = CC0()
}
}
func +(a : CC, b: CC0) -> CC {
return a
}
struct S {
func meth() {}
static func smeth() {}
}
enum E {
case EElem
}
protocol Prot {
func protMeth(_ a: Prot)
}
func foo(_ a: CC, b: E) {
var b = b
_ = b
globV = 0
a + a.instV
a.meth()
CC.smeth()
b = E.EElem
var _: CC
class LocalCC {}
var _: LocalCC
}
typealias CCAlias = CC
extension CC : Prot {
func meth2(_ x: CCAlias) {}
func protMeth(_ a: Prot) {}
var extV : Int { return 0 }
}
class SubCC : CC {}
var globV2: SubCC
class ComputedProperty {
var value : Int {
get {
let result = 0
return result
}
set(newVal) {
// completely ignore it!
}
}
var readOnly : Int { return 0 }
}
class BC2 {
func protMeth(_ a: Prot) {}
}
class SubC2 : BC2, Prot {
override func protMeth(_ a: Prot) {}
}
class CC2 {
subscript (i : Int) -> Int {
get {
return i
}
set(vvv) {
vvv+1
}
}
}
func test1(_ cp: ComputedProperty, sub: CC2) {
var x = cp.value
x = cp.readOnly
cp.value = x
cp.value += 1
x = sub[0]
sub[0] = x
sub[0] += 1
}
struct S2 {
func sfoo() {}
}
var globReadOnly : S2 {
get {
return S2();
}
}
func test2() {
globReadOnly.sfoo()
}
class B1 {
func foo() {}
}
class SB1 : B1 {
override func foo() {
foo()
self.foo()
super.foo()
}
}
func test3(_ c: SB1, s: S2) {
test2()
c.foo()
s.sfoo()
}
func test4(_ a: inout Int) {}
protocol Prot2 {
associatedtype Element
var p : Int { get }
func foo()
}
struct S1 : Prot2 {
typealias Element = Int
var p : Int = 0
func foo() {}
}
func genfoo<T : Prot2 where T.Element == Int>(_ x: T) {}
protocol Prot3 {
func +(x: Self, y: Self)
}
| apache-2.0 | 4aec2ff4eb1efa68b51dc082dd5f9d2f | 11.851613 | 56 | 0.537149 | 2.743802 | false | false | false | false |
n41l/OMChartView | OMChartView/Classes/OMChartLayer.swift | 1 | 1448 | //
// OMChartLayer.swift
// Pods
//
// Created by HuangKun on 16/6/2.
//
//
import UIKit
public class OMChartLayer: CALayer {
var path: OMChartPath?
public var strokeColor: UIColor = UIColor(white: 0.66, alpha: 1)
public var lineWidth: CGFloat = 1
public var lineCap: OMChartLayerLineCap = .Round
public var fillColor: UIColor = UIColor.redColor()
public var yCoordinateScale: CGFloat = 1
var chartStatisticData: ChartStatisticData
public init(_ withChartStatisticData: ChartStatisticData, _ andYCoordinateScale: CGFloat) {
chartStatisticData = withChartStatisticData
yCoordinateScale = andYCoordinateScale
super.init()
}
public required init?(coder aDecoder: NSCoder) {
chartStatisticData = []
super.init(coder: aDecoder)
}
func refineLayer(withRect: CGRect, _ andRectInset: UIEdgeInsets) -> OMChartLayer {
let insetedRect = UIEdgeInsetsInsetRect(withRect, andRectInset)
let tempRect = CGRect(x: andRectInset.left, y: andRectInset.top, width: insetedRect.width, height: insetedRect.height)
path?.rSize = tempRect.size * CGPoint(x: 1, y: yCoordinateScale)
self.frame = CGRect(origin: tempRect.origin + CGPoint(x: 0, y: tempRect.height * (1 - yCoordinateScale)), size: tempRect.size * CGPoint(x: 1, y: yCoordinateScale))
return self
}
public func draw() -> OMChartLayer { return self }
}
| mit | 197eb8017f4f774ed345dc8923b80add | 35.2 | 171 | 0.685083 | 4.01108 | false | false | false | false |
kstaring/swift | validation-test/compiler_crashers_fixed/00336-swift-parser-parsetoplevelcodedecldelayed.swift | 11 | 2475 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
S(T> () -> {
}
print(t: T -> T
}
}
protocol A {
return nil
protocol c = c: A>(b
}
func f<A"
import Foundation
}
class func f(()
class A : U)
func g.d: c
}
}
}
return $0
if true {
}
class B : B<T -> {
class A : P {
}
deinit {
}
S<T -> () {
[T>() ->: d where T) {
}
protocol P {
override init<T! {
e = compose<T -> () -> T! {
typealias R
return g.init(n: U.init(f: c((#object2)()
protocol c : C {
func call()
let t: c: c: P {
}
typealias e == ""A: T>(f<Q<T
typealias F = D>("
var e: A.E == a() {
private let a = compose<I : c) {
struct B<c("A? = b() {
}(v: String {
print() -> T : String = b(x)
let f = B<T>? = b<T>() -> String = compose(f: Int
let f = D> {
return d.d: String = {
self)
}
import Foundation
}
}
struct D : Int = c(b: A")
convenience init<T -> : A: String {
}
}
class func f.init(g<T: A: C> T> Void>>? = Int
typealias B<T) {
}
func g<U : P {
d: AnyObject.init(x: U -> {
func a
var f<T -> T) -> T where A.a("""\()
typealias h: T: C
}
return ")-> Self {
func a()
}
}
}
typealias e {
struct Q<C<T>? = compose(T>()
}
}
self.init(#object2: T.init(false))
import Foundation
}
typealias e : C> T>Bool)-> Int = f: B<U : AnyObject, V, AnyObject) {
d.dynamicType)-> Int -> : d {
return d.c> Int = .e = {
S(("
func f, e: T
c: Array) -> U))
func f.e = .h: d = a(false)
class d<T : A {
}
}
}
import CoreData
let g = nil
class d<T: U -> {
let v: AnyObject, b = .c> Self {
var c
if true {
protocol A where H.E
self.b = T
protocol a {
}
struct e {
var e, g.E
}
self.init()
}
}
extension NSSet {
private class A : A> Int {
protocol P {
}
typealias F = 0
struct D : AnyObject, U.d<A"")
if c {
let i: T>() {
let v: A() {
func f.d<T where g<I : U : AnyObject, f: P> T>>(c: AnyObject) -> S<f = a(x)
}
var d {
}(e: C<H : $0
}
}
let d
func a() ->) {
}
}
}
0
}
}
typealias R
}
import Foundation
protocol b = {
func a
}
init()
import Foundation
}
}
}
import Foundation
}
}
protocol b : a {
class func a
private let i: a {
func f.c == {
}
extension NSSet {
typealias R = nil
}
}
}
func g<Q<f = b<D>(t: P {
}
let d<T.E == A: T.h == a
import Foundation
}
}
static let h
var b: P> Self {
}
self.h
}
| apache-2.0 | 79589c59e07638e15b2633de8f66a2ac | 13.473684 | 78 | 0.580202 | 2.431238 | false | false | false | false |
vincentSuwenliang/Mechandising | MerchandisingSystem/ApiMapper.swift | 1 | 2881 | //
// ApiMapper.swift
// MerchandisingSystem
//
// Created by liang on 26/6/2017.
// Copyright © 2017 beyondz. All rights reserved.
//
import Foundation
import ObjectMapper
////// login ///////
class LoginMapper: BaseMapper {
var response: LoginResponse?
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
super.mapping(map: map)
response <- map["response"]
}
}
////// logout ///////
////// get_update ///////
class ServerUpdateMapper: BaseMapper {
var response: ServerUpdateResponse?
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
super.mapping(map: map)
response <- map["response"]
}
}
// Login Helper
class LoginResponse: Mappable {
var user: User?
var registered_service: [RegisteredService]?
var common_host: String?
var client_host: String?
required init?(map: Map) {
}
func mapping(map: Map) {
user <- map["user"]
registered_service <- map["registered_service"]
common_host <- map["common_host"]
client_host <- map["client_host"]
}
}
class User: TableShared_Time {
var client_id: Int?
var user_id: Int?
var username: String?
var access_level: Int?
var phone: String?
var email: String?
var access_token: String?
var ip_address: String?
var uuid: String?
var client_name: String?
required init?(map: Map) {
super.init(map: map)
}
override func mapping(map: Map) {
super.mapping(map: map)
client_id <- map["client_id"]
user_id <- map["user_id"]
username <- map["username"]
access_level <- map["access_level"]
phone <- map["phone"]
email <- map["email"]
access_token <- map["access_token"]
ip_address <- map["ip_address"]
uuid <- map["uuid"]
client_name <- map["client_name"]
}
}
//class Registered_service: Object {
// dynamic var service_id = 0
// dynamic var client_id = 0
// dynamic var visible = true
// dynamic var creation_time = Date()
// dynamic var last_update_time = Date()
//
// override static func primaryKey() -> String? {
// return "service_id"
// }
//}
class RegisteredService: TableShared_Time {
var service_id: Int?
var client_id: Int?
var expiry_date: Date?
required init?(map: Map) {
super.init(map: map)
print("exec RegisteredService init here", map)
}
override func mapping(map: Map) {
super.mapping(map: map)
service_id <- map["service_id"]
client_id <- map["client_id"]
expiry_date <- (map["expiry_date"], YMDDateTransform())
}
}
| mit | 7f9f65e14129bc99f935690abcb39fd4 | 20.176471 | 63 | 0.559375 | 3.784494 | false | false | false | false |
groue/GRMustache.swift | Sources/JavascriptEscapeHelper.swift | 2 | 5955 | // The MIT License
//
// Copyright (c) 2015 Gwendal Roué
//
// 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
final class JavascriptEscapeHelper : MustacheBoxable {
var mustacheBox: MustacheBox {
// Return a multi-facetted box, because JavascriptEscape interacts in
// various ways with Mustache rendering.
return MustacheBox(
// It has a value:
value: self,
// JavascriptEscape can be used as a filter: {{ javascriptEscape(x) }}:
filter: Filter(filter),
// JavascriptEscape escapes all variable tags: {{# javascriptEscape }}...{{ x }}...{{/ javascriptEscape }}
willRender: willRender)
}
// This function is used for evaluating `javascriptEscape(x)` expressions.
private func filter(_ rendering: Rendering) throws -> Rendering {
return Rendering(JavascriptEscapeHelper.escapeJavascript(rendering.string), rendering.contentType)
}
// A WillRenderFunction: this function lets JavascriptEscape change values that
// are about to be rendered to their escaped counterpart.
//
// It is activated as soon as the formatter enters the context stack, when
// used in a section {{# javascriptEscape }}...{{/ javascriptEscape }}.
private func willRender(_ tag: Tag, box: MustacheBox) -> Any? {
switch tag.type {
case .variable:
// We don't know if the box contains a String, so let's escape its
// rendering.
return { (info: RenderingInfo) -> Rendering in
let rendering = try box.render(info)
return try self.filter(rendering)
}
case .section:
return box
}
}
private class func escapeJavascript(_ string: String) -> String {
// This table comes from https://github.com/django/django/commit/8c4a525871df19163d5bfdf5939eff33b544c2e2#django/template/defaultfilters.py
//
// Quoting Malcolm Tredinnick:
// > Added extra robustness to the escapejs filter so that all invalid
// > characters are correctly escaped. This avoids any chance to inject
// > raw HTML inside <script> tags. Thanks to Mike Wiacek for the patch
// > and Collin Grady for the tests.
//
// Quoting Mike Wiacek from https://code.djangoproject.com/ticket/7177
// > The escapejs filter currently escapes a small subset of characters
// > to prevent JavaScript injection. However, the resulting strings can
// > still contain valid HTML, leading to XSS vulnerabilities. Using hex
// > encoding as opposed to backslash escaping, effectively prevents
// > Javascript injection and also helps prevent XSS. Attached is a
// > small patch that modifies the _js_escapes tuple to use hex encoding
// > on an expanded set of characters.
//
// The initial django commit used `\xNN` syntax. The \u syntax was
// introduced later for JSON compatibility.
let escapeTable: [Character: String] = [
"\0": "\\u0000",
"\u{01}": "\\u0001",
"\u{02}": "\\u0002",
"\u{03}": "\\u0003",
"\u{04}": "\\u0004",
"\u{05}": "\\u0005",
"\u{06}": "\\u0006",
"\u{07}": "\\u0007",
"\u{08}": "\\u0008",
"\u{09}": "\\u0009",
"\u{0A}": "\\u000A",
"\u{0B}": "\\u000B",
"\u{0C}": "\\u000C",
"\u{0D}": "\\u000D",
"\u{0E}": "\\u000E",
"\u{0F}": "\\u000F",
"\u{10}": "\\u0010",
"\u{11}": "\\u0011",
"\u{12}": "\\u0012",
"\u{13}": "\\u0013",
"\u{14}": "\\u0014",
"\u{15}": "\\u0015",
"\u{16}": "\\u0016",
"\u{17}": "\\u0017",
"\u{18}": "\\u0018",
"\u{19}": "\\u0019",
"\u{1A}": "\\u001A",
"\u{1B}": "\\u001B",
"\u{1C}": "\\u001C",
"\u{1D}": "\\u001D",
"\u{1E}": "\\u001E",
"\u{1F}": "\\u001F",
"\\": "\\u005C",
"'": "\\u0027",
"\"": "\\u0022",
">": "\\u003E",
"<": "\\u003C",
"&": "\\u0026",
"=": "\\u003D",
"-": "\\u002D",
";": "\\u003B",
"\u{2028}": "\\u2028",
"\u{2029}": "\\u2029",
// Required to pass GRMustache suite test "`javascript.escape` escapes control characters"
"\r\n": "\\u000D\\u000A",
]
var escaped = ""
for c in string {
if let escapedString = escapeTable[c] {
escaped += escapedString
} else {
escaped.append(c)
}
}
return escaped
}
}
| mit | 035491f446aa123d5f2103fff5308948 | 40.347222 | 147 | 0.554753 | 4.298917 | false | false | false | false |
AppLovin/iOS-SDK-Demo | Swift Demo App/iOS-SDK-Demo/ALDemoRewardedVideosZoneViewController.swift | 1 | 5156 | //
// ALDemoRewardedVideosZoneViewController.swift
// iOS-SDK-Demo-Swift
//
// Created by Suyash Saxena on 6/19/18.
// Copyright © 2018 AppLovin. All rights reserved.
//
import UIKit
class ALDemoRewardedVideosZoneViewController : ALDemoBaseViewController
{
private var incentivizedInterstitial: ALIncentivizedInterstitialAd!
override func viewDidLoad()
{
super.viewDidLoad();
incentivizedInterstitial = ALIncentivizedInterstitialAd(zoneIdentifier: "YOUR_ZONE_ID")
}
@IBAction func showRewardedVideo()
{
// You need to preload each rewarded video before it can be displayed
if incentivizedInterstitial.isReadyForDisplay
{
incentivizedInterstitial.showAndNotify(self)
}
else
{
preloadRewardedVideo()
}
}
// You need to preload each rewarded video before it can be displayed
@IBAction func preloadRewardedVideo()
{
log("Preloading...")
incentivizedInterstitial.preloadAndNotify(self)
}
}
extension ALDemoRewardedVideosZoneViewController : ALAdLoadDelegate
{
// MARK: Ad Load Delegate
func adService(_ adService: ALAdService, didLoad ad: ALAd)
{
log("Rewarded Video Loaded")
}
func adService(_ adService: ALAdService, didFailToLoadAdWithError code: Int32)
{
// Look at ALErrorCodes.h for list of error codes
log("Rewarded video failed to load with error code \(code)")
}
}
extension ALDemoRewardedVideosZoneViewController : ALAdRewardDelegate
{
func rewardValidationRequest(for ad: ALAd, didSucceedWithResponse response: [AnyHashable: Any])
{
/**
* AppLovin servers validated the reward. Refresh user balance from your server. We will also pass the number of coins
* awarded and the name of the currency. However, ideally, you should verify this with your server before granting it.
*/
// "current" - "Coins", "Gold", whatever you set in the dashboard.
// "amount" - "5" or "5.00" if you've specified an amount in the UI.
if let amount = response["amount"] as? NSString, let currencyName = response["currency"] as? NSString
{
log("Rewarded \(amount.floatValue) \(currencyName)")
}
}
func rewardValidationRequest(for ad: ALAd, didFailWithError responseCode: Int)
{
if responseCode == kALErrorCodeIncentivizedUserClosedVideo
{
// Your user exited the video prematurely. It's up to you if you'd still like to grant
// a reward in this case. Most developers choose not to. Note that this case can occur
// after a reward was initially granted (since reward validation happens as soon as a
// video is launched).
}
else if responseCode == kALErrorCodeIncentivizedValidationNetworkTimeout || responseCode == kALErrorCodeIncentivizedUnknownServerError
{
// Some server issue happened here. Don't grant a reward. By default we'll show the user
// a UIAlertView telling them to try again later, but you can change this in the
// Manage Apps UI.
}
else if responseCode == kALErrorCodeIncentiviziedAdNotPreloaded
{
// Indicates that you called for a rewarded video before one was available.
}
log("Reward validation request failed with error code \(responseCode)")
}
func rewardValidationRequest(for ad: ALAd, didExceedQuotaWithResponse response: [AnyHashable: Any])
{
// Your user has already earned the max amount you allowed for the day at this point, so
// don't give them any more money. By default we'll show them a UIAlertView explaining this,
// though you can change that from the Manage Apps UI.
log("Reward validation request did exceed quota with response: \(response)")
}
func rewardValidationRequest(for ad: ALAd, wasRejectedWithResponse response: [AnyHashable: Any])
{
// Your user couldn't be granted a reward for this view. This could happen if you've blacklisted
// them, for example. Don't grant them any currency. By default we'll show them a UIAlertView explaining this,
// though you can change that from the Manage Apps UI.
log("Reward validation request was rejected with response: \(response)")
}
}
extension ALDemoRewardedVideosZoneViewController : ALAdDisplayDelegate
{
func ad(_ ad: ALAd, wasDisplayedIn view: UIView)
{
log("Ad Displayed")
}
func ad(_ ad: ALAd, wasHiddenIn view: UIView)
{
log("Ad Dismissed")
}
func ad(_ ad: ALAd, wasClickedIn view: UIView)
{
log("Ad Clicked")
}
}
extension ALDemoRewardedVideosZoneViewController : ALAdVideoPlaybackDelegate
{
func videoPlaybackBegan(in ad: ALAd)
{
log("Video Started")
}
func videoPlaybackEnded(in ad: ALAd, atPlaybackPercent percentPlayed: NSNumber, fullyWatched wasFullyWatched: Bool)
{
log("Video Ended")
}
}
| mit | 0b3cff7d3f92c9013b9a8c340621abe6 | 34.551724 | 142 | 0.663046 | 4.619176 | false | false | false | false |
peferron/algo | EPI/Stacks and Queues/Evaluate RPN expressions/swift/main.swift | 1 | 1259 | // swiftlint:disable conditional_binding_cascade
enum Token {
case Operator((Int, Int) -> Int)
case Number(Int)
init?(string: String) {
switch string {
case "+":
self = .Operator(+)
case "-":
self = .Operator(-)
case "*":
self = .Operator(*)
case "/":
self = .Operator(/)
default:
if let num = Int(string) {
self = .Number(num)
} else {
return nil
}
}
}
}
public func evaluate(_ expression: String) -> Int? {
let tokens = expression.split(separator: ",").map { Token(string: String($0))! }
var stack = [Token]()
for token in tokens {
switch token {
case let .Operator(op):
let rhsToken = stack.removeLast()
let lhsToken = stack.removeLast()
if case let .Number(lhs) = lhsToken, case let .Number(rhs) = rhsToken {
stack.append(.Number(op(lhs, rhs)))
} else {
return nil
}
case .Number:
stack.append(token)
}
}
if case let .Number(num) = stack.first! {
return num
} else {
return nil
}
}
| mit | 8f9f6d9c940bde9b747f81f871af7d8a | 23.686275 | 84 | 0.468626 | 4.356401 | false | false | false | false |
joshua-d-miller/macOSLAPS | macOSLAPS/Password Tools/LocalPasswordTools.swift | 1 | 6911 | ///
/// LocalPasswordTools.swift
/// macOSLAPS
///
/// Created by Joshua D. Miller on 6/13/17.
///
/// Last Update on June 20, 2022
import Foundation
import OpenDirectory
class LocalTools: NSObject {
class func connect() -> ODRecord {
// Pull Local Administrator Record
do {
let local_node = try ODNode.init(session: ODSession.default(), type: UInt32(kODNodeTypeLocalNodes))
let local_admin_record = try local_node.record(withRecordType: kODRecordTypeUsers, name: Constants.local_admin, attributes: kODAttributeTypeRecordName)
return(local_admin_record)
} catch {
laps_log.print("Unable to connect to local directory node using the administrator account specified. Please check to make sure the administrator account is correct and is available on the system.", .error)
exit(1)
}
}
class func get_expiration_date() -> Date? {
let (_, creation_date) = KeychainService.loadPassword(service: "macOSLAPS")
// Convert the date we received to an acceptable format
if creation_date == "Not Found" {
return(Calendar.current.date(byAdding: .day, value: -7, to: Date()))
} else {
guard let formatted_date = Constants.dateFormatter.date(from: creation_date!) else {
// Print message we were unable to convert the date
laps_log.print("Unable to unwrap the creation date from our keychain entry. Exiting...", .error)
exit(1)
}
let exp_date = Calendar.current.date(byAdding: .day, value: Constants.days_till_expiration, to: formatted_date)!
return exp_date
}
}
class func password_change() {
// Get Configuration Settings
let security_enabled_user = Determine_secureToken()
// Generate random password
var password = PasswordGen(length: Constants.password_length)
var password_meets_requirements = ValidatePassword(generated_password: password)
var password_retry_count = 0
while password_meets_requirements == false && password_retry_count < 10 {
password = PasswordGen(length: Constants.password_length)
password_meets_requirements = ValidatePassword(generated_password: password)
password_retry_count = password_retry_count + 1
}
if password_meets_requirements == false {
laps_log.print("We were unable to generate a password with the requirements specified. Please run macOSLAPS again or change your password requirements", .error)
exit(1)
}
// Pull Local Administrator Record
guard let local_node = try? ODNode.init(session: ODSession.default(), type: UInt32(kODNodeTypeLocalNodes)) else {
laps_log.print("Unable to connect to local node.", .error)
exit(1)
}
guard let local_admin_record = try? local_node.record(withRecordType: kODRecordTypeUsers, name: Constants.local_admin, attributes: kODAttributeTypeRecordName) else {
laps_log.print("Unable to retrieve local administrator record.", .error)
exit(1)
}
// Attempt to load password from System Keychain
let (old_password, _) = KeychainService.loadPassword(service: "macOSLAPS")
// Password Changing Function
if security_enabled_user == true {
// If the attribute is nil then use our first password from config profile to change the password
if old_password == nil || Constants.use_firstpass == true {
do {
laps_log.print("Performing first password change using FirstPass key from configuration profile or string command line argument specified.", .info)
try local_admin_record.changePassword(Constants.first_password, toPassword: password)
} catch {
laps_log.print("Unable to change password for local administrator \(Constants.local_admin) using FirstPassword Key.", .error)
exit(1)
}
}
else {
// Use the System Keychain password to change the old password to the new one and retain secureToken
do {
try local_admin_record.changePassword(old_password, toPassword: password)
} catch {
laps_log.print("Unable to change password for local administrator \(Constants.local_admin) using password loaded from keychain.", .error)
exit(1)
}
}
}
else {
// Do the standard reset as FileVault and secureToken are not present
do {
try local_admin_record.changePassword(nil, toPassword: password)
} catch {
laps_log.print("Unable to reset password for local administrator \(Constants.local_admin).")
}
}
// Write our new password to System Keychain
let save_status : OSStatus = KeychainService.savePassword(service: "macOSLAPS", account: "LAPS Password", data: password)
if save_status == noErr {
laps_log.print("Password change has been completed locally.", .info)
} else {
laps_log.print("We were unable to save the password to keychain so we will revert the changes.", .error)
do {
try local_admin_record.changePassword(password, toPassword: old_password)
exit(1)
} catch {
laps_log.print("Unable to revert back to the old password, Please reset the local administrator account to the FirstPass key and start again", .error)
exit(1)
}
exit(1)
}
// Keychain Removal if enabled
if Constants.remove_keychain == true {
let local_admin_home = local_admin_record.value(forKeyPath: "dsAttrTypeStandard:NFSHomeDirectory") as! NSMutableArray
let local_admin_keychain_path = local_admin_home[0] as! String + "/Library/Keychains"
do {
if FileManager.default.fileExists(atPath: local_admin_keychain_path) {
laps_log.print("Removing Keychain for local administrator account \(Constants.local_admin)...", .info)
try FileManager.default.removeItem(atPath: local_admin_keychain_path)
}
else {
laps_log.print("Keychain does not currently exist. This may be due to the fact that the user account has never been logged into and is only used for elevation...", .info)
}
} catch {
laps_log.print("Unable to remove \(Constants.local_admin)'s Keychain. If logging in as this user you may be presented with prompts for keychain", .warn)
}
}
}
}
| mit | 55c770ca00c763626633cd41ff7766db | 52.573643 | 217 | 0.618579 | 4.766207 | false | false | false | false |
64characters/Telephone | Telephone/IPVersionSettingsMigration.swift | 1 | 2007 | //
// IPVersionSettingsMigration.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2022 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import UseCases
final class IPVersionSettingsMigration {
private let settings: KeyValueSettings
init(settings: KeyValueSettings) {
self.settings = settings
}
}
extension IPVersionSettingsMigration: SettingsMigration {
func execute() {
settings.save(accounts: settings.loadAccounts().map(addingIPVersionIfNeeded))
}
}
private func addingIPVersionIfNeeded(to dict: [String: Any]) -> [String: Any] {
if shouldAddIPVersion(to: dict) {
return removingUseIPv6Only(from: addingIPVersion(to: dict))
} else {
return dict
}
}
private func shouldAddIPVersion(to dict: [String: Any]) -> Bool {
if let version = dict[AKSIPAccountKeys.ipVersion] as? String, !version.isEmpty {
return false
} else {
return true
}
}
private func addingIPVersion(to dict: [String: Any]) -> [String: Any] {
var result = dict
if let useIPv6 = result[AKSIPAccountKeys.useIPv6Only] as? Bool {
result[AKSIPAccountKeys.ipVersion] = useIPv6 ? AKSIPAccountKeys.ipVersion6 : AKSIPAccountKeys.ipVersion4
} else {
result[AKSIPAccountKeys.ipVersion] = AKSIPAccountKeys.ipVersion4
}
return result
}
private func removingUseIPv6Only(from dict: [String: Any]) -> [String: Any] {
var result = dict
result[AKSIPAccountKeys.useIPv6Only] = nil
return result
}
| gpl-3.0 | a2af19f675eb42db8f4019e98dce9b30 | 29.846154 | 112 | 0.707731 | 3.848369 | false | false | false | false |
stevenmirabito/ScavengerHuntApp | Scavenger Hunt/ListViewController.swift | 1 | 6254 | //
// ListViewController.swift
// Scavenger Hunt
//
// Created by Steven Mirabito on 1/26/16.
// Copyright © 2016 StevTek. All rights reserved.
//
import UIKit
class ListViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
let myManager = ItemsManager()
@IBAction func clearList(sender: AnyObject) {
let clearConfirmController = UIAlertController(title: "Are you sure you want to clear the list?", message: "This action cannot be undone.", preferredStyle: .ActionSheet)
let clearYesAction = UIAlertAction(title: "Remove All Items", style: .Destructive) { (action) in
self.myManager.itemsList = [ScavengerHuntItem]();
self.myManager.save()
var indexPathsToDelete = [NSIndexPath]()
if self.tableView.numberOfRowsInSection(0) > 0 {
for i in 0...self.tableView.numberOfRowsInSection(0) - 1 {
indexPathsToDelete.append(NSIndexPath(forRow: i, inSection: 0))
}
self.tableView.deleteRowsAtIndexPaths(indexPathsToDelete, withRowAnimation: .Automatic)
}
}
let clearCancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
clearConfirmController.addAction(clearYesAction)
clearConfirmController.addAction(clearCancelAction)
self.presentViewController(clearConfirmController, animated: true, completion: nil)
}
@IBAction func unwindToList(segue: UIStoryboardSegue){
if segue.identifier == "DoneItem" {
let addVC = segue.sourceViewController as! AddItemViewController
if let newItem = addVC.newItem {
myManager.itemsList += [newItem]
myManager.save()
let indexPath = NSIndexPath(forRow: myManager.itemsList.count - 1, inSection: 0)
tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
}
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myManager.itemsList.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ListViewCell", forIndexPath: indexPath)
let item = myManager.itemsList[indexPath.row]
cell.textLabel?.text = item.name
if(item.completed) {
cell.accessoryType = .Checkmark
if (item.requireImage) {
cell.imageView?.image = item.photo
}
} else {
cell.accessoryType = .None
cell.imageView?.image = nil
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedItem = myManager.itemsList[indexPath.row]
if (!selectedItem.completed) {
if (selectedItem.requireImage) {
let imagePicker = UIImagePickerController()
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera){
imagePicker.sourceType = UIImagePickerControllerSourceType.Camera
} else {
imagePicker.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
}
imagePicker.delegate = self
presentViewController(imagePicker, animated: true, completion: nil)
} else {
selectedItem.completed = true
myManager.save()
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
} else {
var alertMessage = "This action cannot be undone."
if (selectedItem.requireImage) {
alertMessage = "This will permanently delete the attached picture."
}
let uncompleteConfirmController = UIAlertController(title: "Mark as not completed?", message: alertMessage, preferredStyle: .Alert)
let uncompleteYesAction = UIAlertAction(title: "Confirm", style: .Destructive) { (action) in
let selectedItem = self.myManager.itemsList[indexPath.row]
if (selectedItem.requireImage){
selectedItem.photo = nil
} else {
selectedItem.completed = false
}
self.myManager.save()
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
}
let uncompleteCancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)
uncompleteConfirmController.addAction(uncompleteYesAction)
uncompleteConfirmController.addAction(uncompleteCancelAction)
self.presentViewController(uncompleteConfirmController, animated: true, completion: nil)
}
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
myManager.itemsList.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
myManager.save()
}
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let indexPath = tableView.indexPathForSelectedRow {
let selectedItem = myManager.itemsList[indexPath.row]
let photo = info[UIImagePickerControllerOriginalImage] as! UIImage
selectedItem.photo = photo
myManager.save()
dismissViewControllerAnimated(true, completion: {
self.tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
})
}
}
} | mit | e6f45f90203c103c3913fcefc306d942 | 41.835616 | 177 | 0.621941 | 5.865854 | false | false | false | false |
the-grid/Disc | DiscTests/Networking/Resources/User/Identity/AddIdentitySpec.swift | 1 | 5657 | import Disc
import Mockingjay
import MockingjayMatchers
import Nimble
import Quick
import Result
import Swish
class AddIdentitySpec: QuickSpec {
override func spec() {
describe("adding an identity") {
var token: String!
var passport: Disc.APIClient!
var providerAccessToken: String!
var provider: String!
var responseBody: [String: AnyObject]!
var identity: Identity!
beforeEach {
token = "token"
passport = APIClient(token: token)
providerAccessToken = "provider access token"
let bio = "Bear with me...what is a website. Al is helping out, good guy Al."
let description = "Identity only"
let id = 1234
let imageUrl = "https://pbs.twimg.com/profile_images/519492195351408641/vwSKyJtJ_normal.jpeg"
let location = "The Woods"
provider = "twitter"
let url = "https://twitter.com/grid_bear"
let username = "grid_bear"
responseBody = [
"bio": bio,
"description": description,
"id": id,
"image": imageUrl,
"location": location,
"provider": provider,
"url": url,
"username": username
]
identity = Identity(
bio: bio,
description: description,
id: id,
imageUrl: NSURL(string: imageUrl)!,
location: location,
provider: Provider(rawValue: provider)!,
url: NSURL(string: url)!,
username: username
)
}
context("with only an access token") {
it("should result in an identity") {
let requestBody = [
"provider": provider,
"token": providerAccessToken
]
let matcher = api(.POST, "https://passport.thegrid.io/api/user/identities", token: token, body: requestBody)
let builder = json(responseBody)
self.stub(matcher, builder: builder)
var responseValue: Identity?
var responseError: SwishError?
passport.addIdentity(identity.provider, token: providerAccessToken) { result in
responseValue = result.value
responseError = result.error
}
expect(responseValue).toEventually(equal(identity))
expect(responseError).toEventually(beNil())
}
}
context("with an access token and secret") {
it("should result in an identity") {
let providerTokenSecret = "provider token secret"
let requestBody = [
"provider": provider,
"token": providerAccessToken,
"token_secret": providerTokenSecret
]
let matcher = api(.POST, "https://passport.thegrid.io/api/user/identities", token: token, body: requestBody)
let builder = json(responseBody)
self.stub(matcher, builder: builder)
var responseValue: Identity?
var responseError: SwishError?
passport.addIdentity(identity.provider, token: providerAccessToken, secret: providerTokenSecret) { result in
responseValue = result.value
responseError = result.error
}
expect(responseValue).toEventually(equal(identity))
expect(responseError).toEventually(beNil())
}
}
context("with an auth code and redirect URI") {
it("should result in an identity") {
let authCode = "provider auth code"
let redirectUri = "redirect URI"
let requestBody = [
"provider": provider,
"code": authCode,
"redirect_uri": redirectUri
]
let matcher = api(.POST, "https://passport.thegrid.io/api/user/identities", token: token, body: requestBody)
let builder = json(responseBody)
self.stub(matcher, builder: builder)
var responseValue: Identity?
var responseError: SwishError?
passport.addIdentity(identity.provider, code: authCode, redirectUri: redirectUri) { result in
responseValue = result.value
responseError = result.error
}
expect(responseValue).toEventually(equal(identity))
expect(responseError).toEventually(beNil())
}
}
}
}
}
| mit | 6a2ca071a16403ed53822319a6148426 | 39.697842 | 128 | 0.449355 | 6.36333 | false | false | false | false |
Fenrikur/ef-app_ios | Pods/Down/Source/Renderers/DownASTRenderable.swift | 1 | 1894 | //
// DownASTRenderable.swift
// Down
//
// Created by Rob Phillips on 5/31/16.
// Copyright © 2016-2019 Glazed Donut, LLC. All rights reserved.
//
import Foundation
import libcmark
public protocol DownASTRenderable: DownRenderable {
func toAST(_ options: DownOptions) throws -> UnsafeMutablePointer<cmark_node>
}
extension DownASTRenderable {
/// Generates an abstract syntax tree from the `markdownString` property
///
/// - Parameter options: `DownOptions` to modify parsing or rendering, defaulting to `.default`
/// - Returns: An abstract syntax tree representation of the Markdown input
/// - Throws: `MarkdownToASTError` if conversion fails
public func toAST(_ options: DownOptions = .default) throws -> UnsafeMutablePointer<cmark_node> {
return try DownASTRenderer.stringToAST(markdownString, options: options)
}
}
public struct DownASTRenderer {
/// Generates an abstract syntax tree from the given CommonMark Markdown string
///
/// **Important:** It is the caller's responsibility to call `cmark_node_free(ast)` on the returned value
///
/// - Parameters:
/// - string: A string containing CommonMark Markdown
/// - options: `DownOptions` to modify parsing or rendering, defaulting to `.default`
/// - Returns: An abstract syntax tree representation of the Markdown input
/// - Throws: `MarkdownToASTError` if conversion fails
public static func stringToAST(_ string: String, options: DownOptions = .default) throws -> UnsafeMutablePointer<cmark_node> {
var tree: UnsafeMutablePointer<cmark_node>?
string.withCString {
let stringLength = Int(strlen($0))
tree = cmark_parse_document($0, stringLength, options.rawValue)
}
guard let ast = tree else {
throw DownErrors.markdownToASTError
}
return ast
}
}
| mit | 7d633735d88f5e05f4b4738d83c32819 | 37.632653 | 130 | 0.688325 | 4.371824 | false | false | false | false |
raphaelseher/HorizontalCalendarView | example/HorizontalCalendarExample/ViewController.swift | 1 | 3754 | //
// ViewController.swift
// HorizontalCalendarExample
//
// Created by Raphael Seher on 03/01/16.
// Copyright © 2016 Raphael Seher. All rights reserved.
//
import UIKit
import HorizontalCalendarView
class ViewController: UIViewController, HorizontalCalendarDelegate {
@IBOutlet weak var interfaceDesignerCalendarView: HorizontalCalendarView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
addCalendarViewWithConstraints()
addCustomCalendarViewWithConstraint()
interfaceDesignerCalendarView.delegate = self
interfaceDesignerCalendarView.moveToDate(Date(), animated: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func horizontalCalendarViewDidUpdate(_ calendar: HorizontalCalendarView, date: Date) {
let formatter: DateFormatter = DateFormatter()
formatter.dateFormat = "dd.MM.YYYY"
print("Updated calendarView \(formatter.string(from: date))")
}
func addCalendarViewWithConstraints() {
let calendarView = HorizontalCalendarView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 80.0))
calendarView.translatesAutoresizingMaskIntoConstraints = false
calendarView.delegate = self
view.addSubview(calendarView)
let topConstraint = NSLayoutConstraint(item: calendarView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 20)
view.addConstraint(topConstraint)
let heightConstraing = NSLayoutConstraint(item: calendarView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 80)
view.addConstraint(heightConstraing)
let leadingConstraint = NSLayoutConstraint(item: calendarView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0)
view.addConstraint(leadingConstraint)
let trailingConstraint = NSLayoutConstraint(item: calendarView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0)
view.addConstraint(trailingConstraint)
calendarView.moveToDate(Date(), animated: true)
}
func addCustomCalendarViewWithConstraint() {
let customCalendarView = HorizontalCalendarView(frame: CGRect(x: 0, y: 0, width: view.frame.width, height: 100.0), cellWidth: 80, cellClass: MyCustomCalendarCell.self)
customCalendarView.translatesAutoresizingMaskIntoConstraints = false
customCalendarView.delegate = self
customCalendarView.mininumLineSpacing = 1.0
view.addSubview(customCalendarView)
let customTopConstraint = NSLayoutConstraint(item: customCalendarView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 150)
view.addConstraint(customTopConstraint)
let customHeightConstraing = NSLayoutConstraint(item: customCalendarView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1.0, constant: 100)
view.addConstraint(customHeightConstraing)
let customLeadingConstraint = NSLayoutConstraint(item: customCalendarView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0)
view.addConstraint(customLeadingConstraint)
let customTrailingConstraint = NSLayoutConstraint(item: customCalendarView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0)
view.addConstraint(customTrailingConstraint)
customCalendarView.moveToDate(Date(), animated: true)
}
}
| mit | 66dc0e1551583741ec6c895edf4a4e4d | 45.333333 | 189 | 0.757261 | 4.750633 | false | false | false | false |
therealbnut/swift | test/Constraints/diagnostics.swift | 1 | 41068 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype SomeType
}
protocol P2 {
func wonka()
}
extension Int : P {
typealias SomeType = Int
}
extension Double : P {
typealias SomeType = Double
}
func f0(_ x: Int,
_ y: Float) { }
func f1(_: @escaping (Int, Float) -> Int) { }
func f2(_: (_: (Int) -> Int)) -> Int {}
func f3(_: @escaping (_: @escaping (Int) -> Float) -> Int) {}
func f4(_ x: Int) -> Int { }
func f5<T : P2>(_ : T) { }
func f6<T : P, U : P>(_ t: T, _ u: U) where T.SomeType == U.SomeType {}
var i : Int
var d : Double
// Check the various forms of diagnostics the type checker can emit.
// Tuple size mismatch.
f1(
f4 // expected-error {{cannot convert value of type '(Int) -> Int' to expected argument type '(Int, Float) -> Int'}}
)
// Tuple element unused.
f0(i, i,
i) // expected-error{{extra argument in call}}
// Position mismatch
f5(f4) // expected-error {{argument type '(Int) -> Int' does not conform to expected type 'P2'}}
// Tuple element not convertible.
f0(i,
d // expected-error {{cannot convert value of type 'Double' to expected argument type 'Float'}}
)
// Function result not a subtype.
f1(
f0 // expected-error {{cannot convert value of type '(Int, Float) -> ()' to expected argument type '(Int, Float) -> Int'}}
)
f3(
f2 // expected-error {{cannot convert value of type '(@escaping ((Int) -> Int)) -> Int' to expected argument type '(@escaping (Int) -> Float) -> Int'}}
)
f4(i, d) // expected-error {{extra argument in call}}
// Missing member.
i.wobble() // expected-error{{value of type 'Int' has no member 'wobble'}}
// Generic member does not conform.
extension Int {
func wibble<T: P2>(_ x: T, _ y: T) -> T { return x }
func wubble<T>(_ x: (Int) -> T) -> T { return x(self) }
}
i.wibble(3, 4) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Generic member args correct, but return type doesn't match.
struct A : P2 {
func wonka() {}
}
let a = A()
for j in i.wibble(a, a) { // expected-error {{type 'A' does not conform to protocol 'Sequence'}}
}
// Generic as part of function/tuple types
func f6<T:P2>(_ g: (Void) -> T) -> (c: Int, i: T) {
return (c: 0, i: g())
}
func f7() -> (c: Int, v: A) {
let g: (Void) -> A = { return A() }
return f6(g) // expected-error {{cannot convert return expression of type '(c: Int, i: A)' to return type '(c: Int, v: A)'}}
}
func f8<T:P2>(_ n: T, _ f: @escaping (T) -> T) {}
f8(3, f4) // expected-error {{in argument type '(Int) -> Int', 'Int' does not conform to expected type 'P2'}}
typealias Tup = (Int, Double)
func f9(_ x: Tup) -> Tup { return x }
f8((1,2.0), f9) // expected-error {{in argument type '(Tup) -> Tup', 'Tup' (aka '(Int, Double)') does not conform to expected type 'P2'}}
// <rdar://problem/19658691> QoI: Incorrect diagnostic for calling nonexistent members on literals
1.doesntExist(0) // expected-error {{value of type 'Int' has no member 'doesntExist'}}
[1, 2, 3].doesntExist(0) // expected-error {{value of type '[Int]' has no member 'doesntExist'}}
"awfawf".doesntExist(0) // expected-error {{value of type 'String' has no member 'doesntExist'}}
// Does not conform to protocol.
f5(i) // expected-error {{argument type 'Int' does not conform to expected type 'P2'}}
// Make sure we don't leave open existentials when diagnosing.
// <rdar://problem/20598568>
func pancakes(_ p: P2) {
f4(p.wonka) // expected-error{{cannot convert value of type '() -> ()' to expected argument type 'Int'}}
f4(p.wonka()) // expected-error{{cannot convert value of type '()' to expected argument type 'Int'}}
}
protocol Shoes {
static func select(_ subject: Shoes) -> Self
}
// Here the opaque value has type (metatype_type (archetype_type ... ))
func f(_ x: Shoes, asType t: Shoes.Type) {
return t.select(x) // expected-error{{unexpected non-void return value in void function}}
}
precedencegroup Starry {
associativity: left
higherThan: MultiplicationPrecedence
}
infix operator **** : Starry
func ****(_: Int, _: String) { }
i **** i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
infix operator ***~ : Starry
func ***~(_: Int, _: String) { }
i ***~ i // expected-error{{cannot convert value of type 'Int' to expected argument type 'String'}}
@available(*, unavailable, message: "call the 'map()' method on the sequence")
public func myMap<C : Collection, T>(
_ source: C, _ transform: (C.Iterator.Element) -> T
) -> [T] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "call the 'map()' method on the optional value")
public func myMap<T, U>(_ x: T?, _ f: (T) -> U) -> U? {
fatalError("unavailable function can't be called")
}
// <rdar://problem/20142523>
// FIXME: poor diagnostic, to be fixed in 20142462. For now, we just want to
// make sure that it doesn't crash.
func rdar20142523() {
myMap(0..<10, { x in // expected-error{{ambiguous reference to member '..<'}}
()
return x
})
}
// <rdar://problem/21080030> Bad diagnostic for invalid method call in boolean expression: (_, ExpressibleByIntegerLiteral)' is not convertible to 'ExpressibleByIntegerLiteral
func rdar21080030() {
var s = "Hello"
if s.characters.count() == 0 {} // expected-error{{cannot call value of non-function type 'String.CharacterView.IndexDistance'}}{{24-26=}}
}
// <rdar://problem/21248136> QoI: problem with return type inference mis-diagnosed as invalid arguments
func r21248136<T>() -> T { preconditionFailure() } // expected-note 2 {{in call to function 'r21248136'}}
r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
let _ = r21248136() // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/16375647> QoI: Uncallable funcs should be compile time errors
func perform<T>() {} // expected-error {{generic parameter 'T' is not used in function signature}}
// <rdar://problem/17080659> Error Message QOI - wrong return type in an overload
func recArea(_ h: Int, w : Int) {
return h * w // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/17224804> QoI: Error In Ternary Condition is Wrong
func r17224804(_ monthNumber : Int) {
// expected-error @+2 {{binary operator '+' cannot be applied to operands of type 'String' and 'Int'}}
// expected-note @+1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
let monthString = (monthNumber <= 9) ? ("0" + monthNumber) : String(monthNumber)
}
// <rdar://problem/17020197> QoI: Operand of postfix '!' should have optional type; type is 'Int?'
func r17020197(_ x : Int?, y : Int) {
if x! { } // expected-error {{'Int' is not convertible to 'Bool'}}
// <rdar://problem/12939553> QoI: diagnostic for using an integer in a condition is utterly terrible
if y {} // expected-error {{'Int' is not convertible to 'Bool'}}
}
// <rdar://problem/20714480> QoI: Boolean expr not treated as Bool type when function return type is different
func validateSaveButton(_ text: String) {
return (text.characters.count > 0) ? true : false // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/20201968> QoI: poor diagnostic when calling a class method via a metatype
class r20201968C {
func blah() {
r20201968C.blah() // expected-error {{instance member 'blah' cannot be used on type 'r20201968C'; did you mean to use a value of this type instead?}}
}
}
// <rdar://problem/21459429> QoI: Poor compilation error calling assert
func r21459429(_ a : Int) {
assert(a != nil, "ASSERT COMPILATION ERROR")
// expected-warning @-1 {{comparing non-optional value of type 'Int' to nil always returns true}}
}
// <rdar://problem/21362748> [WWDC Lab] QoI: cannot subscript a value of type '[Int]?' with an index of type 'Int'
struct StructWithOptionalArray {
var array: [Int]?
}
func testStructWithOptionalArray(_ foo: StructWithOptionalArray) -> Int {
return foo.array[0] // expected-error {{value of optional type '[Int]?' not unwrapped; did you mean to use '!' or '?'?}} {{19-19=!}}
}
// <rdar://problem/19774755> Incorrect diagnostic for unwrapping non-optional bridged types
var invalidForceUnwrap = Int()! // expected-error {{cannot force unwrap value of non-optional type 'Int'}} {{31-32=}}
// <rdar://problem/20905802> Swift using incorrect diagnostic sometimes on String().asdf
String().asdf // expected-error {{value of type 'String' has no member 'asdf'}}
// <rdar://problem/21553065> Spurious diagnostic: '_' can only appear in a pattern or on the left side of an assignment
protocol r21553065Protocol {}
class r21553065Class<T : AnyObject> {}
_ = r21553065Class<r21553065Protocol>() // expected-error {{type 'r21553065Protocol' does not conform to protocol 'AnyObject'}}
// Type variables not getting erased with nested closures
struct Toe {
let toenail: Nail // expected-error {{use of undeclared type 'Nail'}}
func clip() {
toenail.inspect { x in
toenail.inspect { y in }
}
}
}
// <rdar://problem/21447318> dot'ing through a partially applied member produces poor diagnostic
class r21447318 {
var x = 42
func doThing() -> r21447318 { return self }
}
func test21447318(_ a : r21447318, b : () -> r21447318) {
a.doThing.doThing() // expected-error {{method 'doThing' was used as a property; add () to call it}} {{12-12=()}}
b.doThing() // expected-error {{function 'b' was used as a property; add () to call it}} {{4-4=()}}
}
// <rdar://problem/20409366> Diagnostics for init calls should print the class name
class r20409366C {
init(a : Int) {}
init?(a : r20409366C) {
let req = r20409366C(a: 42)? // expected-error {{cannot use optional chaining on non-optional value of type 'r20409366C'}} {{32-33=}}
}
}
// <rdar://problem/18800223> QoI: wrong compiler error when swift ternary operator branches don't match
func r18800223(_ i : Int) {
// 20099385
_ = i == 0 ? "" : i // expected-error {{result values in '? :' expression have mismatching types 'String' and 'Int'}}
// 19648528
_ = true ? [i] : i // expected-error {{result values in '? :' expression have mismatching types '[Int]' and 'Int'}}
var buttonTextColor: String?
_ = (buttonTextColor != nil) ? 42 : {$0}; // expected-error {{result values in '? :' expression have mismatching types 'Int' and '(_) -> _'}}
}
// <rdar://problem/21883806> Bogus "'_' can only appear in a pattern or on the left side of an assignment" is back
_ = { $0 } // expected-error {{unable to infer closure type in the current context}}
_ = 4() // expected-error {{cannot call value of non-function type 'Int'}}{{6-8=}}
_ = 4(1) // expected-error {{cannot call value of non-function type 'Int'}}
// <rdar://problem/21784170> Incongruous `unexpected trailing closure` error in `init` function which is cast and called without trailing closure.
func rdar21784170() {
let initial = (1.0 as Double, 2.0 as Double)
(Array.init as (Double...) -> Array<Double>)(initial as (Double, Double)) // expected-error {{cannot convert value of type '(Double, Double)' to expected argument type 'Double'}}
}
// <rdar://problem/21829141> BOGUS: unexpected trailing closure
func expect<T, U>(_: T) -> (U.Type) -> Int { return { a in 0 } }
func expect<T, U>(_: T, _: Int = 1) -> (U.Type) -> String { return { a in "String" } }
let expectType1 = expect(Optional(3))(Optional<Int>.self)
let expectType1Check: Int = expectType1
// <rdar://problem/19804707> Swift Enum Scoping Oddity
func rdar19804707() {
enum Op {
case BinaryOperator((Double, Double) -> Double)
}
var knownOps : Op
knownOps = Op.BinaryOperator({$1 - $0})
knownOps = Op.BinaryOperator(){$1 - $0}
knownOps = Op.BinaryOperator{$1 - $0}
knownOps = .BinaryOperator({$1 - $0})
// rdar://19804707 - trailing closures for contextual member references.
knownOps = .BinaryOperator(){$1 - $0}
knownOps = .BinaryOperator{$1 - $0}
_ = knownOps
}
func f7(_ a: Int) -> (_ b: Int) -> Int {
return { b in a+b }
}
_ = f7(1)(1)
f7(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f7(1)(b: 1.0) // expected-error{{extraneous argument label 'b:' in call}}
let f8 = f7(2)
_ = f8(1)
f8(10) // expected-warning {{result of call is unused, but produces 'Int'}}
f8(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
f8(b: 1.0) // expected-error {{extraneous argument label 'b:' in call}}
class CurriedClass {
func method1() {}
func method2(_ a: Int) -> (_ b : Int) -> () { return { b in () } }
func method3(_ a: Int, b : Int) {} // expected-note 5 {{'method3(_:b:)' declared here}}
}
let c = CurriedClass()
_ = c.method1
c.method1(1) // expected-error {{argument passed to call that takes no arguments}}
_ = c.method2(1)
_ = c.method2(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1)(2)
c.method2(1)(c: 2) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(c: 2.0) // expected-error {{extraneous argument label 'c:' in call}}
c.method2(1)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
c.method2(1.0)(2.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method1(c)()
_ = CurriedClass.method1(c)
CurriedClass.method1(c)(1) // expected-error {{argument passed to call that takes no arguments}}
CurriedClass.method1(2.0)(1) // expected-error {{instance member 'method1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(32)(b: 1) // expected-error{{extraneous argument label 'b:' in call}}
_ = CurriedClass.method2(c)
_ = CurriedClass.method2(c)(32)
_ = CurriedClass.method2(1,2) // expected-error {{instance member 'method2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method2(c)(1.0)(b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(1)(1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method2(c)(2)(c: 1.0) // expected-error {{extraneous argument label 'c:'}}
CurriedClass.method3(c)(32, b: 1)
_ = CurriedClass.method3(c)
_ = CurriedClass.method3(c)(1, 2) // expected-error {{missing argument label 'b:' in call}} {{32-32=b: }}
_ = CurriedClass.method3(c)(1, b: 2)(32) // expected-error {{cannot call value of non-function type '()'}}
_ = CurriedClass.method3(1, 2) // expected-error {{instance member 'method3' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
CurriedClass.method3(c)(1.0, b: 1) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
CurriedClass.method3(c)(1) // expected-error {{missing argument for parameter 'b' in call}}
CurriedClass.method3(c)(c: 1.0) // expected-error {{missing argument for parameter 'b' in call}}
extension CurriedClass {
func f() {
method3(1, b: 2)
method3() // expected-error {{missing argument for parameter #1 in call}}
method3(42) // expected-error {{missing argument for parameter 'b' in call}}
method3(self) // expected-error {{missing argument for parameter 'b' in call}}
}
}
extension CurriedClass {
func m1(_ a : Int, b : Int) {}
func m2(_ a : Int) {}
}
// <rdar://problem/23718816> QoI: "Extra argument" error when accidentally currying a method
CurriedClass.m1(2, b: 42) // expected-error {{instance member 'm1' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/22108559> QoI: Confusing error message when calling an instance method as a class method
CurriedClass.m2(12) // expected-error {{instance member 'm2' cannot be used on type 'CurriedClass'; did you mean to use a value of this type instead?}}
// <rdar://problem/20491794> Error message does not tell me what the problem is
enum Color {
case Red
case Unknown(description: String)
static func rainbow() -> Color {}
static func overload(a : Int) -> Color {}
static func overload(b : Int) -> Color {}
static func frob(_ a : Int, b : inout Int) -> Color {}
}
let _: (Int, Color) = [1,2].map({ ($0, .Unknown("")) }) // expected-error {{'map' produces '[T]', not the expected contextual result type '(Int, Color)'}}
let _: [(Int, Color)] = [1,2].map({ ($0, .Unknown("")) })// expected-error {{missing argument label 'description:' in call}} {{51-51=description: }}
let _: [Color] = [1,2].map { _ in .Unknown("") }// expected-error {{missing argument label 'description:' in call}} {{44-44=description: }}
let _: (Int) -> (Int, Color) = { ($0, .Unknown("")) } // expected-error {{missing argument label 'description:' in call}} {{48-48=description: }}
let _: Color = .Unknown("") // expected-error {{missing argument label 'description:' in call}} {{25-25=description: }}
let _: Color = .Unknown // expected-error {{member 'Unknown' expects argument of type '(description: String)'}}
let _: Color = .Unknown(42) // expected-error {{cannot convert value of type 'Int' to expected argument type 'String'}}
let _ : Color = .rainbow(42) // expected-error {{argument passed to call that takes no arguments}}
let _ : (Int, Float) = (42.0, 12) // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
let _ : Color = .rainbow // expected-error {{member 'rainbow' is a function; did you mean to call it?}} {{25-25=()}}
let _: Color = .overload(a : 1.0) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .overload(1.0) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .overload(1) // expected-error {{ambiguous reference to member 'overload'}}
// expected-note @-1 {{overloads for 'overload' exist with these partially matching parameter lists: (a: Int), (b: Int)}}
let _: Color = .frob(1.0, &i) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, b: i) // expected-error {{passing value of type 'Int' to an inout parameter requires explicit '&'}}
let _: Color = .frob(1, &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
let _: Color = .frob(1, b: &d) // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
var someColor : Color = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
someColor = .red // expected-error {{enum type 'Color' has no case 'red'; did you mean 'Red'}}
func testTypeSugar(_ a : Int) {
typealias Stride = Int
let x = Stride(a)
x+"foo" // expected-error {{binary operator '+' cannot be applied to operands of type 'Stride' (aka 'Int') and 'String'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String), (Int, UnsafeMutablePointer<Pointee>), (Int, UnsafePointer<Pointee>)}}
}
// <rdar://problem/21974772> SegFault in FailureDiagnosis::visitInOutExpr
func r21974772(_ y : Int) {
let x = &(1.0 + y) // expected-error {{binary operator '+' cannot be applied to operands of type 'Double' and 'Int'}}
//expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (Double, Double), (UnsafeMutablePointer<Pointee>, Int), (UnsafePointer<Pointee>, Int)}}
}
// <rdar://problem/22020088> QoI: missing member diagnostic on optional gives worse error message than existential/bound generic/etc
protocol r22020088P {}
func r22020088Foo<T>(_ t: T) {}
func r22020088bar(_ p: r22020088P?) {
r22020088Foo(p.fdafs) // expected-error {{value of type 'r22020088P?' has no member 'fdafs'}}
}
// <rdar://problem/22288575> QoI: poor diagnostic involving closure, bad parameter label, and mismatch return type
func f(_ arguments: [String]) -> [ArraySlice<String>] {
return arguments.split(maxSplits: 1, omittingEmptySubsequences: false, whereSeparator: { $0 == "--" })
}
struct AOpts : OptionSet {
let rawValue : Int
}
class B {
func function(_ x : Int8, a : AOpts) {}
func f2(_ a : AOpts) {}
static func f1(_ a : AOpts) {}
}
func test(_ a : B) {
B.f1(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, a: nil) //expected-error {{nil is not compatible with expected argument type 'AOpts'}}
a.function(42, nil) //expected-error {{missing argument label 'a:' in call}}
a.f2(nil) // expected-error {{nil is not compatible with expected argument type 'AOpts'}}
}
// <rdar://problem/21684487> QoI: invalid operator use inside a closure reported as a problem with the closure
typealias MyClosure = ([Int]) -> Bool
func r21684487() {
var closures = Array<MyClosure>()
let testClosure = {(list: [Int]) -> Bool in return true}
let closureIndex = closures.index{$0 === testClosure} // expected-error {{cannot check reference equality of functions; operands here have types '_' and '([Int]) -> Bool'}}
}
// <rdar://problem/18397777> QoI: special case comparisons with nil
func r18397777(_ d : r21447318?) {
let c = r21447318()
if c != nil { // expected-warning {{comparing non-optional value of type 'r21447318' to nil always returns true}}
}
if d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{6-6=(}} {{7-7= != nil)}}
}
if !d { // expected-error {{optional type 'r21447318?' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{8-8= != nil)}}
}
if !Optional(c) { // expected-error {{optional type 'Optional<r21447318>' cannot be used as a boolean; test for '!= nil' instead}} {{7-7=(}} {{18-18= != nil)}}
}
}
// <rdar://problem/22255907> QoI: bad diagnostic if spurious & in argument list
func r22255907_1<T>(_ a : T, b : Int) {}
func r22255907_2<T>(_ x : Int, a : T, b: Int) {}
func reachabilityForInternetConnection() {
var variable: Int = 42
r22255907_1(&variable, b: 2.1) // expected-error {{'&' used with non-inout argument of type 'Int'}} {{15-16=}}
r22255907_2(1, a: &variable, b: 2.1)// expected-error {{'&' used with non-inout argument of type 'Int'}} {{21-22=}}
}
// <rdar://problem/21601687> QoI: Using "=" instead of "==" in if statement leads to incorrect error message
if i = 6 { } // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{6-7===}}
_ = (i = 6) ? 42 : 57 // expected-error {{use of '=' in a boolean context, did you mean '=='?}} {{8-9===}}
// <rdar://problem/22263468> QoI: Not producing specific argument conversion diagnostic for tuple init
func r22263468(_ a : String?) {
typealias MyTuple = (Int, String)
_ = MyTuple(42, a) // expected-error {{value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?}} {{20-20=!}}
}
// rdar://22470302 - Crash with parenthesized call result.
class r22470302Class {
func f() {}
}
func r22470302(_ c: r22470302Class) {
print((c.f)(c)) // expected-error {{argument passed to call that takes no arguments}}
}
// <rdar://problem/21928143> QoI: Pointfree reference to generic initializer in generic context does not compile
extension String {
@available(*, unavailable, message: "calling this is unwise")
func unavail<T : Sequence> // expected-note 2 {{'unavail' has been explicitly marked unavailable here}}
(_ a : T) -> String where T.Iterator.Element == String {}
}
extension Array {
func g() -> String {
return "foo".unavail([""]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
func h() -> String {
return "foo".unavail([0]) // expected-error {{'unavail' is unavailable: calling this is unwise}}
}
}
// <rdar://problem/22519983> QoI: Weird error when failing to infer archetype
func safeAssign<T: RawRepresentable>(_ lhs: inout T) -> Bool {}
// expected-note @-1 {{in call to function 'safeAssign'}}
let a = safeAssign // expected-error {{generic parameter 'T' could not be inferred}}
// <rdar://problem/21692808> QoI: Incorrect 'add ()' fixit with trailing closure
struct Radar21692808<Element> {
init(count: Int, value: Element) {}
}
func radar21692808() -> Radar21692808<Int> {
return Radar21692808<Int>(count: 1) { // expected-error {{cannot invoke initializer for type 'Radar21692808<Int>' with an argument list of type '(count: Int, () -> Int)'}}
// expected-note @-1 {{expected an argument list of type '(count: Int, value: Element)'}}
return 1
}
}
// <rdar://problem/17557899> - This shouldn't suggest calling with ().
func someOtherFunction() {}
func someFunction() -> () {
// Producing an error suggesting that this
return someOtherFunction // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23560128> QoI: trying to mutate an optional dictionary result produces bogus diagnostic
func r23560128() {
var a : (Int,Int)?
a.0 = 42 // expected-error {{value of optional type '(Int, Int)?' not unwrapped; did you mean to use '!' or '?'?}} {{4-4=?}}
}
// <rdar://problem/21890157> QoI: wrong error message when accessing properties on optional structs without unwrapping
struct ExampleStruct21890157 {
var property = "property"
}
var example21890157: ExampleStruct21890157?
example21890157.property = "confusing" // expected-error {{value of optional type 'ExampleStruct21890157?' not unwrapped; did you mean to use '!' or '?'?}} {{16-16=?}}
struct UnaryOp {}
_ = -UnaryOp() // expected-error {{unary operator '-' cannot be applied to an operand of type 'UnaryOp'}}
// expected-note @-1 {{overloads for '-' exist with these partially matching parameter lists: (Float), (Double)}}
// <rdar://problem/23433271> Swift compiler segfault in failure diagnosis
func f23433271(_ x : UnsafePointer<Int>) {}
func segfault23433271(_ a : UnsafeMutableRawPointer) {
f23433271(a[0]) // expected-error {{type 'UnsafeMutableRawPointer' has no subscript members}}
}
// <rdar://problem/23272739> Poor diagnostic due to contextual constraint
func r23272739(_ contentType: String) {
let actualAcceptableContentTypes: Set<String> = []
return actualAcceptableContentTypes.contains(contentType) // expected-error {{unexpected non-void return value in void function}}
}
// <rdar://problem/23641896> QoI: Strings in Swift cannot be indexed directly with integer offsets
func r23641896() {
var g = "Hello World"
g.replaceSubrange(0...2, with: "ce") // expected-error {{cannot invoke 'replaceSubrange' with an argument list of type '(CountableClosedRange<Int>, with: String)'}} expected-note {{overloads for 'replaceSubrange' exist}}
_ = g[12] // expected-error {{'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion}}
}
// <rdar://problem/23718859> QoI: Incorrectly flattening ((Int,Int)) argument list to (Int,Int) when printing note
func test17875634() {
var match: [(Int, Int)] = []
var row = 1
var col = 2
match.append(row, col) // expected-error {{extra argument in call}}
}
// <https://github.com/apple/swift/pull/1205> Improved diagnostics for enums with associated values
enum AssocTest {
case one(Int)
}
if AssocTest.one(1) == AssocTest.one(1) {} // expected-error{{binary operator '==' cannot be applied to two 'AssocTest' operands}}
// expected-note @-1 {{binary operator '==' cannot be synthesized for enums with associated values}}
// <rdar://problem/24251022> Swift 2: Bad Diagnostic Message When Adding Different Integer Types
func r24251022() {
var a = 1
var b: UInt32 = 2
a += a + // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'UInt32'}} expected-note {{expected an argument list of type '(Int, Int)'}}
b
}
func overloadSetResultType(_ a : Int, b : Int) -> Int {
// https://twitter.com/_jlfischer/status/712337382175952896
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
return a == b && 1 == 2 // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/21523291> compiler error message for mutating immutable field is incorrect
func r21523291(_ bytes : UnsafeMutablePointer<UInt8>) {
let i = 42 // expected-note {{change 'let' to 'var' to make it mutable}}
let r = bytes[i++] // expected-error {{cannot pass immutable value as inout argument: 'i' is a 'let' constant}}
}
// SR-1594: Wrong error description when using === on non-class types
class SR1594 {
func sr1594(bytes : UnsafeMutablePointer<Int>, _ i : Int?) {
_ = (i === nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15===}}
_ = (bytes === nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self === nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = (i !== nil) // expected-error {{value of type 'Int?' cannot be compared by reference; did you mean to compare by value?}} {{12-15=!=}}
_ = (bytes !== nil) // expected-error {{type 'UnsafeMutablePointer<Int>' is not optional, value can never be nil}}
_ = (self !== nil) // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
}
func nilComparison(i: Int, o: AnyObject) {
_ = i == nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = nil == i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns false}}
_ = i != nil // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
_ = nil != i // expected-warning {{comparing non-optional value of type 'Int' to nil always returns true}}
_ = i < nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil < i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = i <= nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil <= i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = i > nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil > i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = i >= nil // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = nil >= i // expected-error {{type 'Int' is not optional, value can never be nil}}
_ = o === nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns false}}
_ = o !== nil // expected-warning {{comparing non-optional value of type 'AnyObject' to nil always returns true}}
}
func secondArgumentNotLabeled(a: Int, _ b: Int) { }
secondArgumentNotLabeled(10, 20)
// expected-error@-1 {{missing argument label 'a' in call}}
// <rdar://problem/23709100> QoI: incorrect ambiguity error due to implicit conversion
func testImplConversion(a : Float?) -> Bool {}
func testImplConversion(a : Int?) -> Bool {
let someInt = 42
let a : Int = testImplConversion(someInt) // expected-error {{argument labels '(_:)' do not match any available overloads}}
// expected-note @-1 {{overloads for 'testImplConversion' exist with these partially matching parameter lists: (a: Float?), (a: Int?)}}
}
// <rdar://problem/23752537> QoI: Bogus error message: Binary operator '&&' cannot be applied to two 'Bool' operands
class Foo23752537 {
var title: String?
var message: String?
}
extension Foo23752537 {
func isEquivalent(other: Foo23752537) {
// TODO: <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
// expected-error @+1 {{unexpected non-void return value in void function}}
return (self.title != other.title && self.message != other.message)
}
}
// <rdar://problem/27391581> QoI: Nonsensical "binary operator '&&' cannot be applied to two 'Bool' operands"
func rdar27391581(_ a : Int, b : Int) -> Int {
return a == b && b != 0
// expected-error @-1 {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// <rdar://problem/22276040> QoI: not great error message with "withUnsafePointer" sametype constraints
func read2(_ p: UnsafeMutableRawPointer, maxLength: Int) {}
func read<T : Integer>() -> T? {
var buffer : T
let n = withUnsafePointer(to: &buffer) { (p) in
read2(UnsafePointer(p), maxLength: MemoryLayout<T>.size) // expected-error {{cannot convert value of type 'UnsafePointer<_>' to expected argument type 'UnsafeMutableRawPointer'}}
}
}
func f23213302() {
var s = Set<Int>()
s.subtractInPlace(1) // expected-error {{cannot convert value of type 'Int' to expected argument type 'Set<Int>'}}
}
// <rdar://problem/24202058> QoI: Return of call to overloaded function in void-return context
func rdar24202058(a : Int) {
return a <= 480 // expected-error {{unexpected non-void return value in void function}}
}
// SR-1752: Warning about unused result with ternary operator
struct SR1752 {
func foo() {}
}
let sr1752: SR1752?
true ? nil : sr1752?.foo() // don't generate a warning about unused result since foo returns Void
// <rdar://problem/27891805> QoI: FailureDiagnosis doesn't look through 'try'
struct rdar27891805 {
init(contentsOf: String, encoding: String) throws {}
init(contentsOf: String, usedEncoding: inout String) throws {}
init<T>(_ t: T) {}
}
try rdar27891805(contentsOfURL: nil, usedEncoding: nil)
// expected-error@-1 {{argument labels '(contentsOfURL:, usedEncoding:)' do not match any available overloads}}
// expected-note@-2 {{overloads for 'rdar27891805' exist with these partially matching parameter lists: (contentsOf: String, encoding: String), (contentsOf: String, usedEncoding: inout String)}}
// Make sure RawRepresentable fix-its don't crash in the presence of type variables
class NSCache<K, V> {
func object(forKey: K) -> V? {}
}
class CacheValue {
func value(x: Int) -> Int {} // expected-note {{found this candidate}}
func value(y: String) -> String {} // expected-note {{found this candidate}}
}
func valueForKey<K>(_ key: K) -> CacheValue? {
let cache = NSCache<K, CacheValue>()
return cache.object(forKey: key)?.value // expected-error {{ambiguous reference to member 'value(x:)'}}
}
// SR-2242: poor diagnostic when argument label is omitted
func r27212391(x: Int, _ y: Int) {
let _: Int = x + y
}
func r27212391(a: Int, x: Int, _ y: Int) {
let _: Int = a + x + y
}
r27212391(3, 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #1}}
r27212391(y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}}
r27212391(y: 3, 5) // expected-error {{incorrect argument label in call (have 'y:_:', expected 'x:_:')}}
r27212391(x: 3, x: 5) // expected-error {{extraneous argument label 'x:' in call}}
r27212391(a: 1, 3, y: 5) // expected-error {{missing argument label 'x' in call}}
r27212391(1, x: 3, y: 5) // expected-error {{missing argument label 'a' in call}}
r27212391(a: 1, y: 3, x: 5) // expected-error {{argument 'x' must precede argument 'y'}}
r27212391(a: 1, 3, x: 5) // expected-error {{argument 'x' must precede unnamed argument #2}}
// SR-1255
func foo1255_1() {
return true || false // expected-error {{unexpected non-void return value in void function}}
}
func foo1255_2() -> Int {
return true || false // expected-error {{cannot convert return expression of type 'Bool' to return type 'Int'}}
}
// SR-2505: "Call arguments did not match up" assertion
// Here we're simulating the busted Swift 3 behavior -- see
// test/Constraints/diagnostics_swift4.swift for the correct
// behavior.
func sr_2505(_ a: Any) {} // expected-note {{}}
sr_2505() // expected-error {{missing argument for parameter #1 in call}}
sr_2505(a: 1) // FIXME: emit a warning saying this becomes an error in Swift 4
sr_2505(1, 2) // expected-error {{extra argument in call}}
sr_2505(a: 1, 2) // expected-error {{extra argument in call}}
struct C_2505 {
init(_ arg: Any) {
}
}
protocol P_2505 {
}
extension C_2505 {
init<T>(from: [T]) where T: P_2505 {
}
}
class C2_2505: P_2505 {
}
// FIXME: emit a warning saying this becomes an error in Swift 4
let c_2505 = C_2505(arg: [C2_2505()])
// Diagnostic message for initialization with binary operations as right side
let foo1255_3: String = 1 + 2 + 3 // expected-error {{cannot convert value of type 'Int' to specified type 'String'}}
let foo1255_4: Dictionary<String, String> = ["hello": 1 + 2] // expected-error {{cannot convert value of type 'Int' to expected dictionary value type 'String'}}
let foo1255_5: Dictionary<String, String> = [(1 + 2): "world"] // expected-error {{cannot convert value of type 'Int' to expected dictionary key type 'String'}}
let foo1255_6: [String] = [1 + 2 + 3] // expected-error {{cannot convert value of type 'Int' to expected element type 'String'}}
// SR-2208
struct Foo2208 {
func bar(value: UInt) {}
}
func test2208() {
let foo = Foo2208()
let a: Int = 1
let b: Int = 2
let result = a / b
foo.bar(value: a / b) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: result) // expected-error {{cannot convert value of type 'Int' to expected argument type 'UInt'}}
foo.bar(value: UInt(result)) // Ok
}
// SR-2164: Erroneous diagnostic when unable to infer generic type
struct SR_2164<A, B> { // expected-note 3 {{'B' declared as parameter to type 'SR_2164'}} expected-note 2 {{'A' declared as parameter to type 'SR_2164'}} expected-note * {{generic type 'SR_2164' declared here}}
init(a: A) {}
init(b: B) {}
init(c: Int) {}
init(_ d: A) {}
init(e: A?) {}
}
struct SR_2164_Array<A, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Array'}} expected-note * {{generic type 'SR_2164_Array' declared here}}
init(_ a: [A]) {}
}
struct SR_2164_Dict<A: Hashable, B> { // expected-note {{'B' declared as parameter to type 'SR_2164_Dict'}} expected-note * {{generic type 'SR_2164_Dict' declared here}}
init(a: [A: Double]) {}
}
SR_2164(a: 0) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(b: 1) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(c: 2) // expected-error {{generic parameter 'A' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(3) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Array([4]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164(e: 5) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164_Dict(a: ["pi": 3.14]) // expected-error {{generic parameter 'B' could not be inferred}} expected-note {{explicitly specify the generic arguments to fix this issue}}
SR_2164<Int>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
SR_2164<Int>(b: 1) // expected-error {{generic type 'SR_2164' specialized with too few type parameters (got 1, but expected 2)}}
let _ = SR_2164<Int, Bool>(a: 0) // Ok
let _ = SR_2164<Int, Bool>(b: true) // Ok
SR_2164<Int, Bool, Float>(a: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
SR_2164<Int, Bool, Float>(b: 0) // expected-error {{generic type 'SR_2164' specialized with too many type parameters (got 3, but expected 2)}}
| apache-2.0 | 9fe6ebf68757c2952d50cc2479bfc3eb | 44.030702 | 223 | 0.672981 | 3.618964 | false | false | false | false |
artFintch/Algorithms_and_Data_Structures | DataStructures/LinkedList/LinkedList.swift | 1 | 3203 | //
// LinkedList.swift
// Algorithms and Data Structures
//
// Created by Vyacheslav Khorkov on 26/07/2017.
// Copyright © 2017 Vyacheslav Khorkov. All rights reserved.
//
import Foundation
// Singly linked list without optimisations.
public final class LinkedList<Value> {
// Returns the first value.
// Complexity: O(1)
public var first: Value? { return head?.value }
// Returns the last value.
// Complexity: O(n)
public var last: Value? { return tail?.value }
// Returns true if list is empty.
// Complexity: O(1)
public var isEmpty: Bool { return head == nil }
// Returns the count of values.
// Complexity: O(1)
public private(set) var count = 0
// Appends a new value to the end.
// Complexity: O(n)
public func append(value: Value) {
let newNode = Node(value: value)
if isEmpty {
head = newNode
} else {
tail?.next = newNode
}
count += 1
}
// Inserts a new value at the index.
// Complexity: O(n). If index equals 0: O(1).
@discardableResult public func insert(value: Value, at index: Int) -> Bool {
if index < 0 || index > count { return false }
if index == count {
append(value: value)
return true
}
let newNode = Node(value: value)
let prev = nodeAt(index: index - 1)
if prev == nil {
newNode.next = head
head = newNode
} else {
let next = prev?.next
prev?.next = newNode
newNode.next = next
}
count += 1
return true
}
// Removes all values.
// Complexity: O(1)
public func removeAll() {
head = nil
count = 0
}
// Removes the last value.
// Complexity: O(n)
@discardableResult public func removeLast() -> Value? {
if count <= 1 {
let headValue = head?.value
removeAll()
return headValue
} else {
let beforeTail = nodeAt(index: count - 2)
let tail = beforeTail?.next
beforeTail?.next = nil
count -= 1
return tail?.value
}
}
// Removes a value at the index.
// Complexity: O(n). If index equals 0: O(1).
@discardableResult public func remove(at index: Int) -> Value? {
if index < 0 || index >= count { return nil }
if index == count - 1 { return removeLast() }
if isEmpty { return nil }
let prev = nodeAt(index: index - 1)
let rem = prev?.next ?? head
let next = rem?.next
if index == 0 { head = next }
prev?.next = next
rem?.next = nil
count -= 1
return rem?.value
}
// Returns a value at the index.
// Complexity: O(n)
public subscript(index: Int) -> Value? {
return nodeAt(index: index)?.value
}
// Convenience of use.
private typealias Node = ListNode<Value>
// Linked list node structure.
private final class ListNode<Value> {
let value: Value
var next: Node?
init(value: Value) {
self.value = value
}
}
// Returns head of list.
// Complexity: O(1)
private var head: Node?
// Returns tail of list.
// Complexity: O(n)
private var tail: Node? {
return nodeAt(index: count - 1)
}
// Returns a value at the index.
// Complexity: O(n)
private func nodeAt(index: Int) -> Node? {
if isEmpty { return nil }
if index < 0 || index >= count { return nil }
var i = 0
var cur = head
while i != index {
cur = cur?.next
i += 1
}
return cur
}
}
| mit | 9a045380b062179bc7d2cac503e7b33c | 20.205298 | 77 | 0.626796 | 3.148476 | false | false | false | false |
gribozavr/swift | test/SILGen/lifetime.swift | 1 | 31489 | // RUN: %target-swift-emit-silgen -module-name lifetime -Xllvm -sil-full-demangle -parse-as-library -primary-file %s | %FileCheck %s
struct Buh<T> {
var x: Int {
get {}
set {}
}
}
class Ref {
init() { }
}
struct Val {
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime13local_valtypeyyF
func local_valtype() {
var b: Val
// CHECK: [[B:%[0-9]+]] = alloc_box ${ var Val }
// CHECK: [[MARKED_B:%.*]] = mark_uninitialized [var] [[B]]
// CHECK: destroy_value [[MARKED_B]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime20local_valtype_branch{{[_0-9a-zA-Z]*}}F
func local_valtype_branch(_ a: Bool) {
var a = a
// CHECK: [[A:%[0-9]+]] = alloc_box ${ var Bool }
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: br [[EPILOG:bb[0-9]+]]
var x:Int
// CHECK: [[X:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[MARKED_X:%.*]] = mark_uninitialized [var] [[X]]
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
while a {
// CHECK: cond_br
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK-NOT: destroy_value [[X]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
var y:Int
// CHECK: [[Y:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[MARKED_Y:%.*]] = mark_uninitialized [var] [[Y]]
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK-NOT: destroy_value [[MARKED_X]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
if true {
var z:Int
// CHECK: [[Z:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[MARKED_Z:%.*]] = mark_uninitialized [var] [[Z]]
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Z]]
// CHECK: destroy_value [[MARKED_Y]]
// CHECK-NOT: destroy_value [[MARKED_X]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: br
if a { return }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Z]]
// CHECK: destroy_value [[MARKED_Y]]
// CHECK: destroy_value [[MARKED_X]]
// CHECK: br [[EPILOG]]
// CHECK: destroy_value [[MARKED_Z]]
}
if a { break }
// CHECK: cond_br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK-NOT: destroy_value [[MARKED_X]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: br
// CHECK: {{bb.*:}}
// CHECK: destroy_value [[MARKED_Y]]
// CHECK: br
}
// CHECK: destroy_value [[MARKED_X]]
// CHECK: [[EPILOG]]:
// CHECK: return
}
func reftype_func() -> Ref {}
func reftype_func_with_arg(_ x: Ref) -> Ref {}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime14reftype_returnAA3RefCyF
func reftype_return() -> Ref {
return reftype_func()
// CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref
// CHECK-NOT: destroy_value
// CHECK: [[RET:%[0-9]+]] = apply [[RF]]()
// CHECK-NOT: destroy_value
// CHECK: return [[RET]]
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime11reftype_argyyAA3RefCF : $@convention(thin) (@guaranteed Ref) -> () {
// CHECK: bb0([[A:%[0-9]+]] : @guaranteed $Ref):
// CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK: [[PA:%[0-9]+]] = project_box [[AADDR]]
// CHECK: [[A_COPY:%.*]] = copy_value [[A]]
// CHECK: store [[A_COPY]] to [init] [[PA]]
// CHECK: destroy_value [[AADDR]]
// CHECK-NOT: destroy_value [[A]]
// CHECK: return
// CHECK: } // end sil function '$s8lifetime11reftype_argyyAA3RefCF'
func reftype_arg(_ a: Ref) {
var a = a
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime26reftype_call_ignore_returnyyF
func reftype_call_ignore_return() {
reftype_func()
// CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref
// CHECK-NEXT: [[R:%[0-9]+]] = apply
// CHECK: destroy_value [[R]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime27reftype_call_store_to_localyyF
func reftype_call_store_to_local() {
var a = reftype_func()
// CHECK: [[A:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK-NEXT: [[PB:%.*]] = project_box [[A]]
// CHECK: = function_ref @$s8lifetime12reftype_funcAA3RefCyF : $@convention(thin) () -> @owned Ref
// CHECK-NEXT: [[R:%[0-9]+]] = apply
// CHECK-NOT: copy_value [[R]]
// CHECK: store [[R]] to [init] [[PB]]
// CHECK-NOT: destroy_value [[R]]
// CHECK: destroy_value [[A]]
// CHECK-NOT: destroy_value [[R]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_call_argyyF
func reftype_call_arg() {
reftype_func_with_arg(reftype_func())
// CHECK: [[RF:%[0-9]+]] = function_ref @$s8lifetime12reftype_func{{[_0-9a-zA-Z]*}}F
// CHECK: [[R1:%[0-9]+]] = apply [[RF]]
// CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F
// CHECK: [[R2:%[0-9]+]] = apply [[RFWA]]([[R1]])
// CHECK: destroy_value [[R2]]
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime21reftype_call_with_arg{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[A1:%[0-9]+]] : @guaranteed $Ref):
// CHECK: [[AADDR:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK: [[PB:%.*]] = project_box [[AADDR]]
// CHECK: [[A1_COPY:%.*]] = copy_value [[A1]]
// CHECK: store [[A1_COPY]] to [init] [[PB]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[A2:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[RFWA:%[0-9]+]] = function_ref @$s8lifetime21reftype_func_with_arg{{[_0-9a-zA-Z]*}}F
// CHECK: [[RESULT:%.*]] = apply [[RFWA]]([[A2]])
// CHECK: destroy_value [[RESULT]]
// CHECK: destroy_value [[AADDR]]
// CHECK-NOT: destroy_value [[A1]]
// CHECK: return
func reftype_call_with_arg(_ a: Ref) {
var a = a
reftype_func_with_arg(a)
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime16reftype_reassign{{[_0-9a-zA-Z]*}}F
func reftype_reassign(_ a: inout Ref, b: Ref) {
var b = b
// CHECK: bb0([[AADDR:%[0-9]+]] : $*Ref, [[B1:%[0-9]+]] : @guaranteed $Ref):
// CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var Ref }
// CHECK: [[PBB:%.*]] = project_box [[BADDR]]
a = b
// CHECK: destroy_value
// CHECK: return
}
func tuple_with_ref_elements() -> (Val, (Ref, Val), Ref) {}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime28tuple_with_ref_ignore_returnyyF
func tuple_with_ref_ignore_return() {
tuple_with_ref_elements()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime23tuple_with_ref_elementsAA3ValV_AA3RefC_ADtAFtyF
// CHECK: [[TUPLE:%[0-9]+]] = apply [[FUNC]]
// CHECK: ([[T0:%.*]], [[T1_0:%.*]], [[T1_1:%.*]], [[T2:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: destroy_value [[T2]]
// CHECK: destroy_value [[T1_0]]
// CHECK: return
}
struct Aleph {
var a:Ref
var b:Val
// -- loadable value constructor:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime5AlephV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, @thin Aleph.Type) -> @owned Aleph
// CHECK: bb0([[A:%.*]] : @owned $Ref, [[B:%.*]] : $Val, {{%.*}} : $@thin Aleph.Type):
// CHECK-NEXT: [[RET:%.*]] = struct $Aleph ([[A]] : {{.*}}, [[B]] : {{.*}})
// CHECK-NEXT: return [[RET]]
}
struct Beth {
var a:Val
var b:Aleph
var c:Ref
func gimel() {}
}
protocol Unloadable {}
struct Daleth {
var a:Aleph
var b:Beth
var c:Unloadable
// -- address-only value constructor:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime6DalethV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Aleph, @owned Beth, @in Unloadable, @thin Daleth.Type) -> @out Daleth {
// CHECK: bb0([[THIS:%.*]] : $*Daleth, [[A:%.*]] : @owned $Aleph, [[B:%.*]] : @owned $Beth, [[C:%.*]] : $*Unloadable, {{%.*}} : $@thin Daleth.Type):
// CHECK-NEXT: [[A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.a
// CHECK-NEXT: store [[A]] to [init] [[A_ADDR]]
// CHECK-NEXT: [[B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.b
// CHECK-NEXT: store [[B]] to [init] [[B_ADDR]]
// CHECK-NEXT: [[C_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Daleth, #Daleth.c
// CHECK-NEXT: copy_addr [take] [[C]] to [initialization] [[C_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
class He {
// -- default allocator:
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick He.Type) -> @owned He {
// CHECK: bb0({{%.*}} : $@thick He.Type):
// CHECK-NEXT: [[THIS:%.*]] = alloc_ref $He
// CHECK-NEXT: // function_ref lifetime.He.init
// CHECK-NEXT: [[INIT:%.*]] = function_ref @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He
// CHECK-NEXT: [[THIS1:%.*]] = apply [[INIT]]([[THIS]])
// CHECK-NEXT: return [[THIS1]]
// CHECK-NEXT: }
// -- default initializer:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned He) -> @owned He {
// CHECK: bb0([[SELF:%.*]] : @owned $He):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[UNINITIALIZED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
// CHECK-NEXT: [[UNINITIALIZED_SELF_COPY:%.*]] = copy_value [[UNINITIALIZED_SELF]]
// CHECK-NEXT: destroy_value [[UNINITIALIZED_SELF]]
// CHECK-NEXT: return [[UNINITIALIZED_SELF_COPY]]
// CHECK: } // end sil function '$s8lifetime2HeC{{[_0-9a-zA-Z]*}}fc'
init() { }
}
struct Waw {
var a:(Ref, Val)
var b:Val
// -- loadable value initializer with tuple destructuring:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3WawV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@owned Ref, Val, Val, @thin Waw.Type) -> @owned Waw
// CHECK: bb0([[A0:%.*]] : @owned $Ref, [[A1:%.*]] : $Val, [[B:%.*]] : $Val, {{%.*}} : $@thin Waw.Type):
// CHECK-NEXT: [[A:%.*]] = tuple ([[A0]] : {{.*}}, [[A1]] : {{.*}})
// CHECK-NEXT: [[RET:%.*]] = struct $Waw ([[A]] : {{.*}}, [[B]] : {{.*}})
// CHECK-NEXT: return [[RET]]
}
struct Zayin {
var a:(Unloadable, Val)
var b:Unloadable
// -- address-only value initializer with tuple destructuring:
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime5ZayinV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@in Unloadable, Val, @in Unloadable, @thin Zayin.Type) -> @out Zayin
// CHECK: bb0([[THIS:%.*]] : $*Zayin, [[A0:%.*]] : $*Unloadable, [[A1:%.*]] : $Val, [[B:%.*]] : $*Unloadable, {{%.*}} : $@thin Zayin.Type):
// CHECK-NEXT: [[THIS_A_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.a
// CHECK-NEXT: [[THIS_A0_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 0
// CHECK-NEXT: [[THIS_A1_ADDR:%.*]] = tuple_element_addr [[THIS_A_ADDR]] : {{.*}}, 1
// CHECK-NEXT: copy_addr [take] [[A0]] to [initialization] [[THIS_A0_ADDR]]
// CHECK-NEXT: store [[A1]] to [trivial] [[THIS_A1_ADDR]]
// CHECK-NEXT: [[THIS_B_ADDR:%.*]] = struct_element_addr [[THIS]] : $*Zayin, #Zayin.b
// CHECK-NEXT: copy_addr [take] [[B]] to [initialization] [[THIS_B_ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
}
func fragile_struct_with_ref_elements() -> Beth {}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime29struct_with_ref_ignore_returnyyF
func struct_with_ref_ignore_return() {
fragile_struct_with_ref_elements()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]
// CHECK: destroy_value [[STRUCT]] : $Beth
// CHECK: return
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime28struct_with_ref_materializedyyF
func struct_with_ref_materialized() {
fragile_struct_with_ref_elements().gimel()
// CHECK: [[FUNC:%[0-9]+]] = function_ref @$s8lifetime32fragile_struct_with_ref_elementsAA4BethVyF
// CHECK: [[STRUCT:%[0-9]+]] = apply [[FUNC]]
// CHECK: [[METHOD:%[0-9]+]] = function_ref @$s8lifetime4BethV5gimel{{[_0-9a-zA-Z]*}}F
// CHECK: apply [[METHOD]]([[STRUCT]])
}
class RefWithProp {
var int_prop: Int { get {} set {} }
var aleph_prop: Aleph { get {} set {} }
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime015logical_lvalue_A0yyAA11RefWithPropC_SiAA3ValVtF : $@convention(thin) (@guaranteed RefWithProp, Int, Val) -> () {
func logical_lvalue_lifetime(_ r: RefWithProp, _ i: Int, _ v: Val) {
var r = r
var i = i
var v = v
// CHECK: [[RADDR:%[0-9]+]] = alloc_box ${ var RefWithProp }
// CHECK: [[PR:%[0-9]+]] = project_box [[RADDR]]
// CHECK: [[IADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PI:%[0-9]+]] = project_box [[IADDR]]
// CHECK: store %1 to [trivial] [[PI]]
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var Val }
// CHECK: [[PV:%[0-9]+]] = project_box [[VADDR]]
// -- Reference types need to be copy_valued as property method args.
r.int_prop = i
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]]
// CHECK: [[R1:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[SETTER_METHOD:%[0-9]+]] = class_method {{.*}} : $RefWithProp, #RefWithProp.int_prop!setter.1 : (RefWithProp) -> (Int) -> (), $@convention(method) (Int, @guaranteed RefWithProp) -> ()
// CHECK: apply [[SETTER_METHOD]]({{.*}}, [[R1]])
// CHECK: destroy_value [[R1]]
r.aleph_prop.b = v
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PR]]
// CHECK: [[R2:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[R2BORROW:%[0-9]+]] = begin_borrow [[R2]]
// CHECK: [[MODIFY:%[0-9]+]] = class_method [[R2BORROW]] : $RefWithProp, #RefWithProp.aleph_prop!modify.1 :
// CHECK: ([[ADDR:%.*]], [[TOKEN:%.*]]) = begin_apply [[MODIFY]]([[R2BORROW]])
// CHECK: end_apply [[TOKEN]]
}
func bar() -> Int {}
class Foo<T> {
var x : Int
var y = (Int(), Ref())
var z : T
var w = Ref()
class func makeT() -> T {}
// Class initializer
init() {
// -- allocating entry point
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC :
// CHECK: bb0([[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type):
// CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T>
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc
// CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[THIS]])
// CHECK: return [[INIT_THIS]]
// -- initializing entry point
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc :
// CHECK: bb0([[THISIN:%[0-9]+]] : @owned $Foo<T>):
// CHECK: [[THIS:%[0-9]+]] = mark_uninitialized
// -- initialization for y
// CHECK: [[Y_INIT:%[0-9]+]] = function_ref @$s8lifetime3FooC1ySi_AA3RefCtvpfi : $@convention(thin) <τ_0_0> () -> (Int, @owned Ref)
// CHECK: [[Y_VALUE:%[0-9]+]] = apply [[Y_INIT]]<T>()
// CHECK: ([[Y_EXTRACTED_0:%.*]], [[Y_EXTRACTED_1:%.*]]) = destructure_tuple
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.y
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Y]] : $*(Int, Ref)
// CHECK: [[THIS_Y_0:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 0
// CHECK: assign [[Y_EXTRACTED_0]] to [[THIS_Y_0]]
// CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 1
// CHECK: assign [[Y_EXTRACTED_1]] to [[THIS_Y_1]]
// CHECK: end_access [[WRITE]] : $*(Int, Ref)
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Initialization for w
// CHECK: [[Z_FUNC:%.*]] = function_ref @$s{{.*}}8lifetime3FooC1wAA3RefCvpfi : $@convention(thin) <τ_0_0> () -> @owned Ref
// CHECK: [[Z_RESULT:%.*]] = apply [[Z_FUNC]]<T>()
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]]
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Z]] : $*Ref
// CHECK: assign [[Z_RESULT]] to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Initialization for x
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int
// CHECK: assign {{.*}} to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
x = bar()
z = Foo<T>.makeT()
// CHECK: [[FOOMETA:%[0-9]+]] = metatype $@thick Foo<T>.Type
// CHECK: [[MAKET:%[0-9]+]] = class_method [[FOOMETA]] : {{.*}}, #Foo.makeT!1
// CHECK: ref_element_addr
// -- cleanup this lvalue and return this
// CHECK: [[THIS_RESULT:%.*]] = copy_value [[THIS]]
// -- TODO: This copy should be unnecessary.
// CHECK: destroy_value [[THIS]]
// CHECK: return [[THIS_RESULT]]
}
init(chi:Int) {
var chi = chi
z = Foo<T>.makeT()
// -- allocating entry point
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC :
// CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[METATYPE:%[0-9]+]] : $@thick Foo<T>.Type):
// CHECK: [[THIS:%[0-9]+]] = alloc_ref $Foo<T>
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc
// CHECK: [[INIT_THIS:%[0-9]+]] = apply [[INIT_METHOD]]<{{.*}}>([[CHI]], [[THIS]])
// CHECK: return [[INIT_THIS]]
// -- initializing entry point
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC3chiACyxGSi_tcfc : $@convention(method) <T> (Int, @owned Foo<T>) -> @owned Foo<T> {
// CHECK: bb0([[CHI:%[0-9]+]] : $Int, [[THISIN:%[0-9]+]] : @owned $Foo<T>):
// CHECK: [[THIS:%[0-9]+]] = mark_uninitialized [rootself] [[THISIN]]
// -- First we initialize #Foo.y.
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Y:%.*]] = ref_element_addr [[BORROWED_THIS]] : $Foo<T>, #Foo.y
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Y]] : $*(Int, Ref)
// CHECK: [[THIS_Y_1:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 0
// CHECK: assign {{.*}} to [[THIS_Y_1]] : $*Int
// CHECK: [[THIS_Y_2:%.*]] = tuple_element_addr [[WRITE]] : $*(Int, Ref), 1
// CHECK: assign {{.*}} to [[THIS_Y_2]] : $*Ref
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Then we create a box that we will use to perform a copy_addr into #Foo.x a bit later.
// CHECK: [[CHIADDR:%[0-9]+]] = alloc_box ${ var Int }, var, name "chi"
// CHECK: [[PCHI:%[0-9]+]] = project_box [[CHIADDR]]
// CHECK: store [[CHI]] to [trivial] [[PCHI]]
// -- Then we initialize #Foo.z
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[THIS_Z:%.*]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.z
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_Z]] : $*T
// CHECK: copy_addr [take] {{.*}} to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- Then initialize #Foo.x using the earlier stored value of CHI to THIS_Z.
x = chi
// CHECK: [[BORROWED_THIS:%.*]] = begin_borrow [[THIS]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PCHI]]
// CHECK: [[X:%.*]] = load [trivial] [[READ]]
// CHECK: [[THIS_X:%[0-9]+]] = ref_element_addr [[BORROWED_THIS]] : {{.*}}, #Foo.x
// CHECK: [[WRITE:%.*]] = begin_access [modify] [dynamic] [[THIS_X]] : $*Int
// CHECK: assign [[X]] to [[WRITE]]
// CHECK: end_borrow [[BORROWED_THIS]]
// -- cleanup chi
// CHECK: destroy_value [[CHIADDR]]
// -- Then begin the epilogue sequence
// CHECK: [[THIS_RETURN:%.*]] = copy_value [[THIS]]
// CHECK: destroy_value [[THIS]]
// CHECK: return [[THIS_RETURN]]
// CHECK: } // end sil function '$s8lifetime3FooC3chiACyxGSi_tcfc'
}
// -- allocating entry point
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fC :
// CHECK: [[INIT_METHOD:%[0-9]+]] = function_ref @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc
// -- initializing entry point
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooC{{[_0-9a-zA-Z]*}}fc :
init<U:Intifiable>(chi:U) {
z = Foo<T>.makeT()
x = chi.intify()
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfd : $@convention(method) <T> (@guaranteed Foo<T>) -> @owned Builtin.NativeObject
deinit {
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $Foo<T>):
bar()
// CHECK: function_ref @$s8lifetime3barSiyF
// CHECK: apply
// -- don't need to destroy_value x because it's trivial
// CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #Foo.x
// -- destroy_value y
// CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.y
// CHECK: [[YADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[YADDR]]
// CHECK: destroy_addr [[YADDR_ACCESS]]
// CHECK: end_access [[YADDR_ACCESS]]
// -- destroy_value z
// CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.z
// CHECK: [[ZADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[ZADDR]]
// CHECK: destroy_addr [[ZADDR_ACCESS]]
// CHECK: end_access [[ZADDR_ACCESS]]
// -- destroy_value w
// CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #Foo.w
// CHECK: [[WADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[WADDR]]
// CHECK: destroy_addr [[WADDR_ACCESS]]
// CHECK: end_access [[WADDR_ACCESS]]
// -- return back this
// CHECK: [[PTR:%.*]] = unchecked_ref_cast [[THIS]] : $Foo<T> to $Builtin.NativeObject
// CHECK: [[PTR_OWNED:%.*]] = unchecked_ownership_conversion [[PTR]] : $Builtin.NativeObject, @guaranteed to @owned
// CHECK: return [[PTR_OWNED]]
// CHECK: } // end sil function '$s8lifetime3FooCfd'
}
// Deallocating destructor for Foo.
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3FooCfD : $@convention(method) <T> (@owned Foo<T>) -> ()
// CHECK: bb0([[SELF:%[0-9]+]] : @owned $Foo<T>):
// CHECK: [[DESTROYING_REF:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK-NEXT: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK-NEXT: [[RESULT_SELF:%[0-9]+]] = apply [[DESTROYING_REF]]<T>([[BORROWED_SELF]]) : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK-NEXT: end_borrow [[BORROWED_SELF]]
// CHECK-NEXT: end_lifetime [[SELF]]
// CHECK-NEXT: [[SELF:%[0-9]+]] = unchecked_ref_cast [[RESULT_SELF]] : $Builtin.NativeObject to $Foo<T>
// CHECK-NEXT: dealloc_ref [[SELF]] : $Foo<T>
// CHECK-NEXT: [[RESULT:%[0-9]+]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: } // end sil function '$s8lifetime3FooCfD'
}
class FooSubclass<T> : Foo<T> {
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime11FooSubclassCfd : $@convention(method) <T> (@guaranteed FooSubclass<T>) -> @owned Builtin.NativeObject
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $FooSubclass<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $Foo<T>
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime3FooCfd : $@convention(method) <τ_0_0> (@guaranteed Foo<τ_0_0>) -> @owned Builtin.NativeObject
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<T>([[BASE]])
// CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]]
// CHECK: end_borrow [[BORROWED_PTR]]
// CHECK: return [[PTR]]
deinit {
bar()
}
}
class ImplicitDtor {
var x:Int
var y:(Int, Ref)
var w:Ref
init() { }
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime12ImplicitDtorCfd
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtor):
// -- don't need to destroy_value x because it's trivial
// CHECK-NOT: ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.x
// -- destroy_value y
// CHECK: [[YADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.y
// CHECK: [[YADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[YADDR]]
// CHECK: destroy_addr [[YADDR_ACCESS]]
// CHECK: end_access [[YADDR_ACCESS]]
// -- destroy_value w
// CHECK: [[WADDR:%[0-9]+]] = ref_element_addr [[THIS]] : {{.*}}, #ImplicitDtor.w
// CHECK: [[WADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[WADDR]]
// CHECK: destroy_addr [[WADDR_ACCESS]]
// CHECK: end_access [[WADDR_ACCESS]]
// CHECK: return
}
class ImplicitDtorDerived<T> : ImplicitDtor {
var z:T
init(z : T) {
super.init()
self.z = z
}
// CHECK: sil hidden [ossa] @$s8lifetime19ImplicitDtorDerivedCfd : $@convention(method) <T> (@guaranteed ImplicitDtorDerived<T>) -> @owned Builtin.NativeObject {
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerived<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtor
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime12ImplicitDtorCfd
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]([[BASE]])
// -- destroy_value z
// CHECK: [[BORROWED_PTR:%.*]] = begin_borrow [[PTR]]
// CHECK: [[CAST_BORROWED_PTR:%.*]] = unchecked_ref_cast [[BORROWED_PTR]] : $Builtin.NativeObject to $ImplicitDtorDerived<T>
// CHECK: [[ZADDR:%[0-9]+]] = ref_element_addr [[CAST_BORROWED_PTR]] : {{.*}}, #ImplicitDtorDerived.z
// CHECK: [[ZADDR_ACCESS:%.*]] = begin_access [deinit] [static] [[ZADDR]]
// CHECK: destroy_addr [[ZADDR_ACCESS]]
// CHECK: end_access [[ZADDR_ACCESS]]
// CHECK: end_borrow [[BORROWED_PTR]]
// -- epilog
// CHECK-NOT: unchecked_ref_cast
// CHECK-NOT: unchecked_ownership_conversion
// CHECK: return [[PTR]]
}
class ImplicitDtorDerivedFromGeneric<T> : ImplicitDtorDerived<Int> {
init() { super.init(z: 5) }
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime30ImplicitDtorDerivedFromGenericC{{[_0-9a-zA-Z]*}}fc
// CHECK: bb0([[THIS:%[0-9]+]] : @guaranteed $ImplicitDtorDerivedFromGeneric<T>):
// -- base dtor
// CHECK: [[BASE:%[0-9]+]] = upcast [[THIS]] : ${{.*}} to $ImplicitDtorDerived<Int>
// CHECK: [[BASE_DTOR:%[0-9]+]] = function_ref @$s8lifetime19ImplicitDtorDerivedCfd
// CHECK: [[PTR:%.*]] = apply [[BASE_DTOR]]<Int>([[BASE]])
// CHECK: return [[PTR]]
}
protocol Intifiable {
func intify() -> Int
}
struct Bar {
var x:Int
// Loadable struct initializer
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BarV{{[_0-9a-zA-Z]*}}fC
init() {
// CHECK: bb0([[METATYPE:%[0-9]+]] : $@thin Bar.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var Bar }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
x = bar()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]]
// CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bar, #Bar.x
// CHECK: assign {{.*}} to [[SELF_X]]
// -- load and return this
// CHECK: [[SELF_VAL:%[0-9]+]] = load [trivial] [[PB_BOX]]
// CHECK: destroy_value [[MARKED_SELF_BOX]]
// CHECK: return [[SELF_VAL]]
}
init<T:Intifiable>(xx:T) {
x = xx.intify()
}
}
struct Bas<T> {
var x:Int
var y:T
// Address-only struct initializer
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime3BasV{{[_0-9a-zA-Z]*}}fC
init(yy:T) {
// CHECK: bb0([[THISADDRPTR:%[0-9]+]] : $*Bas<T>, [[YYADDR:%[0-9]+]] : $*T, [[META:%[0-9]+]] : $@thin Bas<T>.Type):
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box $<τ_0_0> { var Bas<τ_0_0> } <T>
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [rootself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%.*]] = project_box [[MARKED_SELF_BOX]]
x = bar()
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]]
// CHECK: [[SELF_X:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.x
// CHECK: assign {{.*}} to [[SELF_X]]
y = yy
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[PB_BOX]]
// CHECK: [[SELF_Y:%[0-9]+]] = struct_element_addr [[WRITE]] : $*Bas<T>, #Bas.y
// CHECK: copy_addr {{.*}} to [[SELF_Y]]
// CHECK: destroy_value
// -- 'self' was emplaced into indirect return slot
// CHECK: return
}
init<U:Intifiable>(xx:U, yy:T) {
x = xx.intify()
y = yy
}
}
class B { init(y:Int) {} }
class D : B {
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime1DC1x1yACSi_Sitcfc
// CHECK: bb0([[X:%[0-9]+]] : $Int, [[Y:%[0-9]+]] : $Int, [[SELF:%[0-9]+]] : @owned $D):
init(x: Int, y: Int) {
var x = x
var y = y
// CHECK: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var D }
// CHECK: [[MARKED_SELF_BOX:%[0-9]+]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK: [[PB_BOX:%[0-9]+]] = project_box [[MARKED_SELF_BOX]]
// CHECK: store [[SELF]] to [init] [[PB_BOX]]
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PX:%[0-9]+]] = project_box [[XADDR]]
// CHECK: store [[X]] to [trivial] [[PX]]
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[PY:%[0-9]+]] = project_box [[YADDR]]
// CHECK: store [[Y]] to [trivial] [[PY]]
super.init(y: y)
// CHECK: [[THIS1:%[0-9]+]] = load [take] [[PB_BOX]]
// CHECK: [[THIS1_SUP:%[0-9]+]] = upcast [[THIS1]] : ${{.*}} to $B
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PY]]
// CHECK: [[Y:%[0-9]+]] = load [trivial] [[READ]]
// CHECK: [[SUPER_CTOR:%[0-9]+]] = function_ref @$s8lifetime1BC1yACSi_tcfc : $@convention(method) (Int, @owned B) -> @owned B
// CHECK: [[THIS2_SUP:%[0-9]+]] = apply [[SUPER_CTOR]]([[Y]], [[THIS1_SUP]])
// CHECK: [[THIS2:%[0-9]+]] = unchecked_ref_cast [[THIS2_SUP]] : $B to $D
// CHECK: [[THIS1:%[0-9]+]] = load [copy] [[PB_BOX]]
// CHECK: destroy_value [[MARKED_SELF_BOX]]
}
func foo() {}
}
// CHECK-LABEL: sil hidden [ossa] @$s8lifetime8downcast{{[_0-9a-zA-Z]*}}F
func downcast(_ b: B) {
var b = b
// CHECK: [[BADDR:%[0-9]+]] = alloc_box ${ var B }
// CHECK: [[PB:%[0-9]+]] = project_box [[BADDR]]
(b as! D).foo()
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PB]]
// CHECK: [[B:%[0-9]+]] = load [copy] [[READ]]
// CHECK: [[D:%[0-9]+]] = unconditional_checked_cast [[B]] : {{.*}} to D
// CHECK: apply {{.*}}([[D]])
// CHECK-NOT: destroy_value [[B]]
// CHECK: destroy_value [[D]]
// CHECK: destroy_value [[BADDR]]
// CHECK: return
}
func int(_ x: Int) {}
func ref(_ x: Ref) {}
func tuple() -> (Int, Ref) { return (1, Ref()) }
func tuple_explosion() {
int(tuple().0)
// CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF
// CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]()
// CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: destroy_value [[T1]]
// CHECK-NOT: destructure_tuple [[TUPLE]]
// CHECK-NOT: tuple_extract [[TUPLE]]
// CHECK-NOT: destroy_value
ref(tuple().1)
// CHECK: [[F:%[0-9]+]] = function_ref @$s8lifetime5tupleSi_AA3RefCtyF
// CHECK: [[TUPLE:%[0-9]+]] = apply [[F]]()
// CHECK: ({{%.*}}, [[T1:%.*]]) = destructure_tuple [[TUPLE]]
// CHECK: destroy_value [[T1]]
// CHECK-NOT: destructure_tuple [[TUPLE]]
// CHECK-NOT: tuple_extract [[TUPLE]]
// CHECK-NOT: destroy_value [[TUPLE]]
}
| apache-2.0 | 79380c95b23184354c58a9b5f399149a | 39.254476 | 196 | 0.54881 | 3.045569 | false | false | false | false |
fweissi/WatchDogsSignup | Sources/App/Models/Member.swift | 1 | 1042 | import Vapor
import Fluent
import HTTP
final class Member: Model {
var id: Node?
var exists: Bool = false
var name: String
var email: String
init(name: String, email: String) {
self.id = nil
self.name = name
self.email = email
}
init(node: Node, in context: Context) throws {
id = try node.extract("id")
name = try node.extract("name")
email = try node.extract("email")
}
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"name": name,
"email": email
])
}
}
extension Member: Preparation {
static func prepare(_ database: Database) throws {
try database.create("members", closure: { member in
member.id()
member.string("name")
member.string("email")
})
}
static func revert(_ database: Database) throws {
try database.delete("members")
}
}
| mit | 7694877f2a660abd86656590dfc8dd40 | 19.431373 | 59 | 0.525912 | 4.359833 | false | false | false | false |
broadwaylamb/Codable | Sources/Calendar+Codable.swift | 1 | 5107 | //
// Calendar+Codable.swift
// Codable
//
// Created by Sergej Jaskiewicz on 31/07/2017.
//
//
import Foundation
#if swift(>=3.2)
#else
extension Calendar : Codable {
internal static func _toNSCalendarIdentifier(_ identifier : Identifier) -> NSCalendar.Identifier {
if #available(OSX 10.10, iOS 8.0, *) {
let identifierMap : [Identifier : NSCalendar.Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.iso8601 : .ISO8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina,
.islamicTabular : .islamicTabular,
.islamicUmmAlQura : .islamicUmmAlQura]
return identifierMap[identifier]!
} else {
let identifierMap : [Identifier : NSCalendar.Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.iso8601 : .ISO8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina]
return identifierMap[identifier]!
}
}
internal static func _fromNSCalendarIdentifier(_ identifier : NSCalendar.Identifier) -> Identifier {
if #available(OSX 10.10, iOS 8.0, *) {
let identifierMap : [NSCalendar.Identifier : Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.ISO8601 : .iso8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina,
.islamicTabular : .islamicTabular,
.islamicUmmAlQura : .islamicUmmAlQura]
return identifierMap[identifier]!
} else {
let identifierMap : [NSCalendar.Identifier : Identifier] =
[.gregorian : .gregorian,
.buddhist : .buddhist,
.chinese : .chinese,
.coptic : .coptic,
.ethiopicAmeteMihret : .ethiopicAmeteMihret,
.ethiopicAmeteAlem : .ethiopicAmeteAlem,
.hebrew : .hebrew,
.ISO8601 : .iso8601,
.indian : .indian,
.islamic : .islamic,
.islamicCivil : .islamicCivil,
.japanese : .japanese,
.persian : .persian,
.republicOfChina : .republicOfChina]
return identifierMap[identifier]!
}
}
private enum CodingKeys : Int, CodingKey {
case identifier
case locale
case timeZone
case firstWeekday
case minimumDaysInFirstWeek
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let identifierString = try container.decode(String.self, forKey: .identifier)
let identifier = Calendar._fromNSCalendarIdentifier(NSCalendar.Identifier(rawValue: identifierString))
self.init(identifier: identifier)
self.locale = try container.decodeIfPresent(Locale.self, forKey: .locale)
self.timeZone = try container.decode(TimeZone.self, forKey: .timeZone)
self.firstWeekday = try container.decode(Int.self, forKey: .firstWeekday)
self.minimumDaysInFirstWeek = try container.decode(Int.self, forKey: .minimumDaysInFirstWeek)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
let identifier = Calendar._toNSCalendarIdentifier(self.identifier).rawValue
try container.encode(identifier, forKey: .identifier)
try container.encode(self.locale, forKey: .locale)
try container.encode(self.timeZone, forKey: .timeZone)
try container.encode(self.firstWeekday, forKey: .firstWeekday)
try container.encode(self.minimumDaysInFirstWeek, forKey: .minimumDaysInFirstWeek)
}
}
#endif
| mit | 7e1e485c3a595d67c58d1505014842b9 | 38.898438 | 110 | 0.560407 | 5.336468 | false | false | false | false |
PlutoMa/SwiftProjects | 007.Simple Photo Browser/SimplePhotoBrowser/SimplePhotoBrowser/ViewController.swift | 1 | 1008 | //
// ViewController.swift
// SimplePhotoBrowser
//
// Created by Dareway on 2017/10/18.
// Copyright © 2017年 Pluto. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let scrollView = UIScrollView()
let imageView = UIImageView()
override func viewDidLoad() {
super.viewDidLoad()
imageView.frame = view.bounds
imageView.isUserInteractionEnabled = true
imageView.image = UIImage(named: "samplePhoto.jpeg")
scrollView.frame = view.bounds
scrollView.backgroundColor = UIColor.white
scrollView.maximumZoomScale = 4.0
scrollView.minimumZoomScale = 1.0
scrollView.contentSize = imageView.frame.size
scrollView.delegate = self
scrollView.addSubview(imageView)
view.addSubview(scrollView)
}
}
extension ViewController: UIScrollViewDelegate {
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
}
| mit | 2137d45082e0c69be7837440286c38ea | 24.125 | 65 | 0.668657 | 5 | false | false | false | false |
kenwilcox/Swift-Linux | Hello/Sources/main.swift | 1 | 521 | import Foundation
#if os(Linux)
import Glibc
#endif
srandom(UInt32(Date().timeIntervalSince1970))
if CommandLine.arguments.count == 1 {
print("Usage: \(CommandLine.arguments[0]) NAME")
let randInt = (random() % 20) + 1
let fact = factorial(n: randInt)
print("Random Factorial: factorial(\(randInt)) = \(fact)")
} else {
//let name = CommandLine.arguments[1]
let args = CommandLine.arguments[1..<CommandLine.arguments.count];
let name = args.joined(separator: " ")
sayHello(name: name)
}
| mit | 3cec8551a1b3099db985f0f07eb7ccdd | 27.944444 | 70 | 0.675624 | 3.568493 | false | false | false | false |
emilstahl/swift | test/NameBinding/Inputs/has_accessibility.swift | 20 | 598 | public let x: Int = 0
internal let y: Int = 0
private let z: Int = 0
#if DEFINE_VAR_FOR_SCOPED_IMPORT
internal let zz: Int = 0
#endif
public struct Foo {
internal init() {}
public static func x() {}
internal static func y() {}
private static func z() {}
}
public class Base {
internal func method() {}
public internal(set) var value = 0
}
public class HiddenMethod {
internal func method() {}
}
public class HiddenType {
typealias TheType = Int
}
public struct OriginallyEmpty {}
public struct StructWithPrivateSetter {
public private(set) var x = 0
public init() {}
}
| apache-2.0 | 199f3ab39613c07e401016ec21a82105 | 15.611111 | 39 | 0.680602 | 3.538462 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/DAO/BatchFetch/Galleries/GalleriesQueueBatchFetcher.swift | 1 | 5525 | //
// GalleriesQueueBatchFetcher.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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.
//
class GalleriesQueueBatchFetcher: Cancelable {
private let pageSize = 100
private let requestSender: RequestSender
private let userId: String?
private let query: String?
private let sort: SortOrder?
private let completion: GalleriesBatchClosure?
private let filter: GalleriesRequestFilter?
private var operationQueue: OperationQueue?
private var firstRequestHandler: RequestHandler?
private var objectsByPage: Dictionary<PagingData, Array<Gallery>>
private var errorsByPage: Dictionary<PagingData, APIClientError>
init(requestSender: RequestSender, userId: String?, query: String?, sort: SortOrder?, filter: GalleriesRequestFilter?, completion: GalleriesBatchClosure?) {
self.requestSender = requestSender
self.userId = userId
self.sort = sort
self.query = query
self.completion = completion
self.filter = filter
self.objectsByPage = Dictionary<PagingData, Array<Gallery>>()
self.errorsByPage = Dictionary<PagingData, APIClientError>()
}
func cancel() {
operationQueue?.cancelAllOperations()
firstRequestHandler?.cancel()
}
func fetch() -> RequestHandler {
guard operationQueue == nil
else {
assert(false) //Fetch should be called only once
return RequestHandler(object: self)
}
let request = GalleriesRequest(page: 1, perPage: pageSize, sort: sort, filter: filter, userId: userId, query: query)
let handler = GalleriesResponseHandler {
[weak self](galleries, pagingInfo, error) -> (Void) in
guard let strongSelf = self
else { return }
if let galleries = galleries,
let pagingInfo = pagingInfo {
strongSelf.objectsByPage[PagingData(page: 1, pageSize: strongSelf.pageSize)] = galleries
strongSelf.prepareBlockOperations(pagingInfo: pagingInfo)
} else {
strongSelf.completion?(nil, error)
}
}
firstRequestHandler = requestSender.send(request, withResponseHandler: handler)
return RequestHandler(object: self)
}
private func prepareBlockOperations(pagingInfo: PagingInfo) {
operationQueue = OperationQueue()
operationQueue!.maxConcurrentOperationCount = 4
let finishOperation = BlockOperation()
finishOperation.addExecutionBlock {
[unowned finishOperation, weak self] in
guard let strongSelf = self else { return }
if finishOperation.isCancelled {
strongSelf.completion?(nil, APIClientError.genericError(code: APIClientError.OperationCancelledCode))
return
}
DispatchQueue.main.async {
[weak self] in
guard let strongSelf = self else { return }
let objects = strongSelf.objectsByPage.sorted(by: { $0.key.page > $1.key.page }).flatMap({ $0.value })
let error = strongSelf.errorsByPage.values.first
strongSelf.completion?(objects, error)
}
}
if pagingInfo.totalPages > 1 {
for page in 2...pagingInfo.totalPages {
let pagingData = PagingData(page: page, pageSize: pageSize)
let operation = GalleriesBatchFetchOperation(requestSender: requestSender, userId: userId, query: query, sort: sort, filter: filter, pagingData: pagingData) {
[weak self](operation, error) in
guard let strongSelf = self,
let operation = operation as? GalleriesBatchFetchOperation
else { return }
if let galleries = operation.galleries {
strongSelf.objectsByPage[operation.pagingData] = galleries
}
if let error = error as? APIClientError {
strongSelf.errorsByPage[operation.pagingData] = error
}
}
finishOperation.addDependency(operation)
operationQueue!.addOperation(operation)
}
}
operationQueue!.addOperation(finishOperation)
}
}
| mit | 601cce62617f985834b99008c8c5bcad | 40.856061 | 174 | 0.641991 | 5.202448 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01296-resolvetypedecl.swift | 1 | 732 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func f<l>() -> (l, l -> l) -> l {
l j l.n = {
}
{
l) {
n }
}
protocol f {
}
class l: f{ class func n {}
func a<i>() {
b b {
}
}
class a<f : b, l : b m f.l == l> {
}
protocol b {
}
struct j<n : b> : b {
}
typealias
d = i
}
class d<j : i, f : i where j.i == f> : e {
}
class d<j, f> {
}
protocol i {
}
protocol e {
}
protocol i : d {
| apache-2.0 | 29b6738d21eb95b0b15b760c7e7ae1e5 | 17.3 | 79 | 0.614754 | 2.72119 | false | false | false | false |
jalehman/twitter-clone | TwitterClient/ComposeTweetViewController.swift | 1 | 4506 | //
// ComposeTweetViewController.swift
// TwitterClient
//
// Created by Josh Lehman on 2/22/15.
// Copyright (c) 2015 Josh Lehman. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController {
// MARK: Properties
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var screenNameLabel: UILabel!
@IBOutlet weak var tweetTextView: UITextView!
var cancelButton: UIBarButtonItem!
var tweetButton: UIBarButtonItem!
var countdownButton: UIBarButtonItem!
private let viewModel: ComposeTweetViewModel
private var hairlineImage: UIImageView?
// MARK: API
init(viewModel: ComposeTweetViewModel) {
self.viewModel = viewModel
super.init(nibName: "ComposeTweetViewController", bundle: nil)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: UIViewController Overrides
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = .None
hairlineImage = findHairlineImageViewUnder(navigationController!.navigationBar)
let disabledTextAttributes = [NSForegroundColorAttributeName: UIColor.lightGrayColor()]
let enabledTextAttributes = [NSForegroundColorAttributeName: UIColor(red: 0.361, green: 0.686, blue: 0.925, alpha: 1)]
cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: nil, action: "")
cancelButton.setTitleTextAttributes(enabledTextAttributes, forState: .Normal)
self.navigationItem.leftBarButtonItem = cancelButton
tweetButton = UIBarButtonItem(title: "Tweet", style: .Bordered, target: nil, action: "")
tweetButton.setTitleTextAttributes(enabledTextAttributes, forState: .Normal)
tweetButton.setTitleTextAttributes(disabledTextAttributes, forState: .Disabled)
countdownButton = UIBarButtonItem(title: "140", style: .Bordered, target: nil, action: "")
countdownButton.setTitleTextAttributes(disabledTextAttributes, forState: .Normal)
countdownButton.setTitleTextAttributes(disabledTextAttributes, forState: .Disabled)
countdownButton.enabled = false
navigationItem.rightBarButtonItems = [tweetButton, countdownButton]
navigationController?.navigationBar.barTintColor = UIColor(red: 0.996, green: 0.996, blue: 0.996, alpha: 1.0)
navigationController?.navigationBar.translucent = false
avatarImage.layer.cornerRadius = 5.0
avatarImage.clipsToBounds = true
navigationController?.navigationBar.titleTextAttributes = enabledTextAttributes
tweetTextView.becomeFirstResponder()
bindViewModel()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
hairlineImage?.hidden = true
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
hairlineImage?.hidden = false
}
// MARK: Private
private func bindViewModel() {
avatarImage.setImageWithURL(NSURL(string: User.currentUser!.profileImageUrl!))
userNameLabel.text = User.currentUser!.name!
screenNameLabel.text = User.currentUser!.screenname!
cancelButton.rac_command = viewModel.executeCancelComposeTweet
tweetButton.rac_command = viewModel.executeComposeTweet
if viewModel.replyToUserScreenname != nil {
self.title = "R: @\(viewModel.replyToUserScreenname!)"
}
RAC(viewModel, "tweetText") << tweetTextView.rac_textSignal()
.doNextAs { (text: NSString) in
UIView.setAnimationsEnabled(false)
self.countdownButton.title = String(self.viewModel.characterLimit - text.length)
UIView.setAnimationsEnabled(true)
}
}
private func findHairlineImageViewUnder(view: UIView) -> UIImageView? {
if (view.isKindOfClass(UIImageView) && view.bounds.size.height <= 1.0) {
return view as? UIImageView
}
for subview in view.subviews {
let imageView = self.findHairlineImageViewUnder(subview as! UIView)
if imageView != nil {
return imageView
}
}
return nil
}
}
| gpl-2.0 | abd7fde30bdba791c87b852898431097 | 35.934426 | 126 | 0.666667 | 5.428916 | false | false | false | false |
dshahidehpour/IGListKit | Examples/Examples-iOS/IGListKitExamples/ViewControllers/DisplayViewController.swift | 4 | 1769 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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.
*/
import UIKit
import IGListKit
class DisplayViewController: UIViewController, IGListAdapterDataSource {
lazy var adapter: IGListAdapter = {
return IGListAdapter(updater: IGListAdapterUpdater(), viewController: self, workingRangeSize: 0)
}()
let collectionView = IGListCollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(collectionView)
adapter.collectionView = collectionView
adapter.dataSource = self
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
collectionView.frame = view.bounds
}
// MARK: IGListAdapterDataSource
func objects(for listAdapter: IGListAdapter) -> [IGListDiffable] {
return [1, 2, 3, 4, 5, 6] as [NSNumber]
}
func listAdapter(_ listAdapter: IGListAdapter, sectionControllerFor object: Any) -> IGListSectionController {
return DisplaySectionController()
}
func emptyView(for listAdapter: IGListAdapter) -> UIView? { return nil }
}
| bsd-3-clause | f402cd7d7236585f01a11cef2f2a6845 | 35.102041 | 113 | 0.73714 | 5.344411 | false | false | false | false |
touchopia/HackingWithSwift | project36/Project36/GameViewController.swift | 1 | 1421 | //
// GameViewController.swift
// Project36
//
// Created by TwoStraws on 25/08/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
view.showsPhysics = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| unlicense | 94f4cd4bb91d043dc17f9b006acb9689 | 24.357143 | 77 | 0.583099 | 5.461538 | false | false | false | false |
tkremenek/swift | test/SourceKit/CodeFormat/indent-multiline-string-interp.swift | 16 | 1413 | let s1 = """
\(
45
)
"""
let s2 = """
\(
45
)
"""
let s3 = """
\(
45
)
"""
let s4 = """
foo \( 45 /*
comment content
*/) bar
"""
// RUN: %sourcekitd-test -req=format -line=2 %s >%t.response
// RUN: %sourcekitd-test -req=format -line=3 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=4 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=8 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=9 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=10 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=14 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=15 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=16 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=20 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=21 %s >>%t.response
// RUN: %sourcekitd-test -req=format -line=22 %s >>%t.response
// RUN: %FileCheck --strict-whitespace %s <%t.response
// CHECK: key.sourcetext: " \\("
// CHECK: key.sourcetext: " 45"
// CHECK: key.sourcetext: " )"
// CHECK: key.sourcetext: " \\("
// CHECK: key.sourcetext: " 45"
// CHECK: key.sourcetext: " )"
// CHECK: key.sourcetext: " \\("
// CHECK: key.sourcetext: " 45"
// CHECK: key.sourcetext: ")"
// CHECK: key.sourcetext: " foo \\( 45 /*"
// CHECK: key.sourcetext: " comment content"
// CHECK: key.sourcetext: " */) bar"
| apache-2.0 | 9bb59023d5bc145366ee98d41b0bc331 | 23.789474 | 62 | 0.586695 | 2.843058 | false | true | false | false |
aschwaighofer/swift | test/ImportResolution/import-resolution-overload.swift | 2 | 2498 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/overload_intFunctions.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/overload_boolFunctions.swift
// RUN: %target-swift-frontend -emit-module -o %t %S/Inputs/overload_vars.swift
// RUN: %target-swift-frontend -typecheck %s -I %t -sdk "" -verify -swift-version 4
// RUN: %target-swift-frontend -typecheck %s -I %t -sdk "" -verify -swift-version 5
// RUN: not %target-swift-frontend -dump-ast %s -I %t -sdk "" > %t.astdump
// RUN: %FileCheck %s < %t.astdump
import overload_intFunctions
import overload_boolFunctions
import overload_vars
import var overload_vars.scopedVar
import func overload_boolFunctions.scopedFunction
struct LocalType {}
func something(_ obj: LocalType) -> LocalType { return obj }
func something(_ a: Int, _ b: Int, _ c: Int) -> () {}
var _ : Bool = something(true)
var _ : Int = something(1)
var _ : (Int, Int) = something(1, 2)
var _ : LocalType = something(LocalType())
var _ : () = something(1, 2, 3)
something = 42
let ambValue = ambiguousWithVar // no-warning - var preferred
let ambValueChecked: Int = ambValue
ambiguousWithVar = 42 // no-warning
ambiguousWithVar(true) // no-warning
var localVar : Bool
localVar = false
localVar = 42 // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
localVar(42) // expected-error {{cannot call value of non-function type 'Bool'}}
var _ : localVar // should still work
_ = scopedVar // no-warning
scopedVar(42)
var _ : Bool = scopedFunction(true)
var _ : Int = scopedFunction(42)
scopedFunction = 42
// FIXME: Should be an error -- a type name and a function cannot overload.
var _ : Int = TypeNameWins(42)
TypeNameWins = 42 // expected-error {{no exact matches in reference to global function 'TypeNameWins'}}
var _ : TypeNameWins // no-warning
// rdar://problem/21739333
protocol HasFooSub : HasFoo { }
extension HasFooSub {
var foo: Int { return 0 }
}
// CHECK-LABEL: func_decl{{.*}}"testHasFooSub(_:)"
func testHasFooSub(_ hfs: HasFooSub) -> Int {
// CHECK: return_stmt
// CHECK-NOT: func_decl
// CHECK: member_ref_expr{{.*}}decl=overload_vars.(file).HasFoo.foo
return hfs.foo
}
extension HasBar {
var bar: Int { return 0 }
}
// CHECK-LABEL: func_decl{{.*}}"testHasBar(_:)"
func testHasBar(_ hb: HasBar) -> Int {
// CHECK: return_stmt
// CHECK-NOT: func_decl
// CHECK: member_ref_expr{{.*}}decl=overload_vars.(file).HasBar.bar
return hb.bar
}
| apache-2.0 | af844252f9ea7d3bfdec1c89fffe894a | 30.620253 | 103 | 0.686549 | 3.239948 | false | true | false | false |
csujedihy/SwiftDSSocket | Tests/SwiftDSSocketTests/KernelCommunication.swift | 1 | 2344 | //
// KernelCommunication.swift
// SwiftDSSocket
//
// Created by Yi Huang on 7/31/17.
// Copyright © 2017 Yi Huang. All rights reserved.
//
import XCTest
@testable import SwiftDSSocket
class KernelCommunication: XCTestCase {
var client: SwiftDSSocket?
weak var echoExpectation: XCTestExpectation?
let serverAddress = "com.proximac.kext"
let ClientTag = 1
let packet = "helloworld"
override func setUp() {
super.setUp()
client = SwiftDSSocket(delegate: self, delegateQueue: .main, type: .kernel)
}
override func tearDown() {
super.tearDown()
client?.disconnect()
}
/*:
**Note:**
Unable to run kernel communication test in CI due to some system restrictions.
To test this functionality in real system, you need to write a kernel extension.
However, you can try this one written by myself for testing.
```
static errno_t proximac_ctl_send_func(kern_ctl_ref kctlref, u_int32_t unit, void *unitinfo, mbuf_t m, int flags) {
size_t buf_len = mbuf_len(m);
char *data = mbuf_data(m);
ctl_enqueuedata(kctlref, unit, data, buf_len, 0);
mbuf_free(m);
return 0;
}
```
Uncomment code below to enable testing in real system
*/
// func testExample() {
// try? client?.tryConnect(tobundleName: serverAddress)
// echoExpectation = expectation(description: "Finished Communication with Kernel")
// waitForExpectations(timeout: 10) { (error) in
// if let error = error {
// XCTFail("Failed Kernel Communication error: \(error.localizedDescription)")
// }
// }
// }
}
extension KernelCommunication: SwiftDSSocketDelegate {
func socket(sock: SwiftDSSocket, didRead data: Data, tag: Int) {
if data.count == packet.characters.count {
if let content = String(bytes: data, encoding: .utf8) {
if content == packet {
SwiftDSSocket.log("Found data from kernel: \(content)")
echoExpectation?.fulfill()
}
}
}
}
func socket(sock: SwiftDSSocket, didConnectToHost host: String, port: UInt16) {
SwiftDSSocket.log("@didConnectToHost (kernel)")
let dataToSend = packet.data(using: .utf8)
sock.readData(toLength: UInt(packet.characters.count), tag: ClientTag)
if let dataToSend = dataToSend {
sock.write(data: dataToSend, tag: ClientTag)
}
}
}
| mit | 6d7ed0b660c73861bf20226aad70c2b0 | 27.228916 | 116 | 0.66752 | 3.760835 | false | true | false | false |
apple/swift-algorithms | Sources/Algorithms/Partition.swift | 1 | 12204 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Algorithms open source project
//
// Copyright (c) 2020-2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// stablePartition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements satisfying `belongsInSecondPartition` into a suffix of
/// the collection, preserving their relative order, and returns the start of
/// the resulting suffix.
///
/// - Complexity: O(*n* log *n*), where *n* is the number of elements.
/// - Precondition:
/// `n == distance(from: range.lowerBound, to: range.upperBound)`
@inlinable
internal mutating func stablePartition(
count n: Int,
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
if n == 0 { return subrange.lowerBound }
if n == 1 {
return try belongsInSecondPartition(self[subrange.lowerBound])
? subrange.lowerBound
: subrange.upperBound
}
let h = n / 2, i = index(subrange.lowerBound, offsetBy: h)
let j = try stablePartition(
count: h,
subrange: subrange.lowerBound..<i,
by: belongsInSecondPartition)
let k = try stablePartition(
count: n - h,
subrange: i..<subrange.upperBound,
by: belongsInSecondPartition)
return rotate(subrange: j..<k, toStartAt: i)
}
/// Moves all elements satisfying the given predicate into a suffix of the
/// given range, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
///
/// - Parameters:
/// - subrange: The range of elements within this collection to partition.
/// - belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
try stablePartition(
count: distance(from: subrange.lowerBound, to: subrange.upperBound),
subrange: subrange,
by: belongsInSecondPartition)
}
/// Moves all elements satisfying the given predicate into a suffix of this
/// collection, preserving the relative order of the elements in both
/// partitions, and returns the start of the resulting suffix.
///
/// - Parameter belongsInSecondPartition: A predicate used to partition the
/// collection. All elements satisfying this predicate are ordered after
/// all elements not satisfying it.
///
/// - Complexity: O(*n* log *n*), where *n* is the length of this collection.
@inlinable
public mutating func stablePartition(
by belongsInSecondPartition: (Element) throws-> Bool
) rethrows -> Index {
try stablePartition(
subrange: startIndex..<endIndex,
by: belongsInSecondPartition)
}
}
//===----------------------------------------------------------------------===//
// partition(by:)
//===----------------------------------------------------------------------===//
extension MutableCollection {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
// This version of `partition(subrange:)` is half stable; the elements in
// the first partition retain their original relative order.
guard var i = try self[subrange].firstIndex(where: belongsInSecondPartition)
else { return subrange.upperBound }
var j = index(after: i)
while j != subrange.upperBound {
if try !belongsInSecondPartition(self[j]) {
swapAt(i, j)
formIndex(after: &i)
}
formIndex(after: &j)
}
return i
}
}
extension MutableCollection where Self: BidirectionalCollection {
/// Moves all elements satisfying `isSuffixElement` into a suffix of the
/// collection, returning the start position of the resulting suffix.
///
/// - Complexity: O(*n*) where n is the length of the collection.
@inlinable
public mutating func partition(
subrange: Range<Index>,
by belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var lo = subrange.lowerBound
var hi = subrange.upperBound
// 'Loop' invariants (at start of Loop, all are true):
// * lo < hi
// * predicate(self[i]) == false, for i in startIndex ..< lo
// * predicate(self[i]) == true, for i in hi ..< endIndex
Loop: while true {
FindLo: do {
while lo < hi {
if try belongsInSecondPartition(self[lo]) { break FindLo }
formIndex(after: &lo)
}
break Loop
}
FindHi: do {
formIndex(before: &hi)
while lo < hi {
if try !belongsInSecondPartition(self[hi]) { break FindHi }
formIndex(before: &hi)
}
break Loop
}
swapAt(lo, hi)
formIndex(after: &lo)
}
return lo
}
}
//===----------------------------------------------------------------------===//
// partitioningIndex(where:)
//===----------------------------------------------------------------------===//
extension Collection {
/// Returns the start index of the partition of a collection that matches
/// the given predicate.
///
/// The collection must already be partitioned according to the predicate.
/// That is, there should be an index `i` where for every element in
/// `collection[..<i]` the predicate is `false`, and for every element in
/// `collection[i...]` the predicate is `true`.
///
/// - Parameter belongsInSecondPartition: A predicate that partitions the
/// collection.
/// - Returns: The index of the first element in the collection for which
/// `predicate` returns `true`, or `endIndex` if there are no elements
/// for which `predicate` returns `true`.
///
/// - Complexity: O(log *n*), where *n* is the length of this collection if
/// the collection conforms to `RandomAccessCollection`, otherwise O(*n*).
@inlinable
public func partitioningIndex(
where belongsInSecondPartition: (Element) throws -> Bool
) rethrows -> Index {
var n = count
var l = startIndex
while n > 0 {
let half = n / 2
let mid = index(l, offsetBy: half)
if try belongsInSecondPartition(self[mid]) {
n = half
} else {
l = index(after: mid)
n -= half + 1
}
}
return l
}
}
//===----------------------------------------------------------------------===//
// partitioned(by:)
//===----------------------------------------------------------------------===//
extension Sequence {
/// Returns two arrays containing, in order, the elements of the sequence that
/// do and don’t satisfy the given predicate.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters:
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
/// print(longNames)
/// // Prints "["Vivien", "Marlon"]"
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns a Boolean value indicating whether the element
/// should be included in the second returned array. Otherwise, the element
/// will appear in the first returned array.
///
/// - Returns: Two arrays with all of the elements of the receiver. The
/// first array contains all the elements that `predicate` didn’t allow, and
/// the second array contains all the elements that `predicate` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the sequence.
@inlinable
public func partitioned(
by predicate: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
var lhs = [Element]()
var rhs = [Element]()
for element in self {
if try predicate(element) {
rhs.append(element)
} else {
lhs.append(element)
}
}
return (lhs, rhs)
}
}
extension Collection {
/// Returns two arrays containing, in order, the elements of the collection
/// that do and don’t satisfy the given predicate.
///
/// In this example, `partitioned(by:)` is used to separate the input based on
/// whether a name is shorter than five characters.
///
/// let cast = ["Vivien", "Marlon", "Kim", "Karl"]
/// let (longNames, shortNames) = cast.partitioned(by: { $0.count < 5 })
/// print(longNames)
/// // Prints "["Vivien", "Marlon"]"
/// print(shortNames)
/// // Prints "["Kim", "Karl"]"
///
/// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns a Boolean value indicating whether the element
/// should be included in the second returned array. Otherwise, the element
/// will appear in the first returned array.
///
/// - Returns: Two arrays with all of the elements of the receiver. The
/// first array contains all the elements that `predicate` didn’t allow, and
/// the second array contains all the elements that `predicate` allowed.
///
/// - Complexity: O(*n*), where *n* is the length of the collection.
@inlinable
public func partitioned(
by predicate: (Element) throws -> Bool
) rethrows -> (falseElements: [Element], trueElements: [Element]) {
guard !self.isEmpty else {
return ([], [])
}
// Since collections have known sizes, we can allocate one array of size
// `self.count`, then insert items at the beginning or end of that contiguous
// block. This way, we don’t have to do any dynamic array resizing. Since we
// insert the right elements on the right side in reverse order, we need to
// reverse them back to the original order at the end.
let count = self.count
// Inside of the `initializer` closure, we set what the actual mid-point is.
// We will use this to partition the single array into two.
var midPoint: Int = 0
let elements = try [Element](
unsafeUninitializedCapacity: count,
initializingWith: { buffer, initializedCount in
var lhs = buffer.baseAddress!
var rhs = lhs + buffer.count
do {
for element in self {
if try predicate(element) {
rhs -= 1
rhs.initialize(to: element)
} else {
lhs.initialize(to: element)
lhs += 1
}
}
precondition(lhs == rhs, """
Collection's `count` differed from the number of elements iterated.
"""
)
let rhsIndex = rhs - buffer.baseAddress!
buffer[rhsIndex...].reverse()
initializedCount = buffer.count
midPoint = rhsIndex
} catch {
let lhsCount = lhs - buffer.baseAddress!
let rhsCount = (buffer.baseAddress! + buffer.count) - rhs
buffer.baseAddress!.deinitialize(count: lhsCount)
rhs.deinitialize(count: rhsCount)
throw error
}
})
let lhs = elements[..<midPoint]
let rhs = elements[midPoint...]
return (
Array(lhs),
Array(rhs)
)
}
}
| apache-2.0 | b70ceb2321c6b7ae560b3dc0ff7ce5ae | 34.759531 | 81 | 0.594391 | 4.724525 | false | false | false | false |
gogunskiy/The-Name | NameMe/Classes/UserInterface/ViewControllers/NMNameDetailsViewController/views/NMNameDetailsTitleCell.swift | 1 | 1301 | //
// NMNameDetailsTitleCell
// NameMe
//
// Created by Vladimir Gogunsky on 1/9/15.
// Copyright (c) 2015 Volodymyr Hohunskyi. All rights reserved.
//
import UIKit
class NMNameDetailsTitleCell : NMNameDetailsBaseCell {
weak var delegate: NMNameDetailsTitleCellDelegate?
@IBOutlet var nameLabel : UILabel!
@IBOutlet var originLabel : UILabel!
@IBOutlet var ratingLabel : UILabel!
@IBOutlet var sexLabel : UILabel!
@IBOutlet var favButton : UIButton!
override func awakeFromNib() {
self.height = 88.0
}
override func update(nameDetails: NMNameItem?) {
nameLabel.text = nameDetails?.name
originLabel.text = NEDataManager.sharedInstance.originName(nameDetails!.origin!)
ratingLabel.text = nameDetails?.rating
sexLabel.text = nameDetails?.sex
}
func updateOrigin(origin: NSString) {
originLabel.text = origin
}
func updateFavoriteButton(selected: Bool) {
favButton.selected = selected
}
@IBAction func favoriteButtonAction(sender : UIButton) {
delegate!.favoriveButtonWasClickedWithState(sender.selected)
}
}
protocol NMNameDetailsTitleCellDelegate : NSObjectProtocol {
func favoriveButtonWasClickedWithState(state: Bool)
} | mit | b1db562d990a47d655d6d95f728d1ff9 | 24.038462 | 88 | 0.687932 | 4.47079 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Gutenberg/GutenbergMediaInserterHelper.swift | 1 | 11714 | import Foundation
import CoreServices
import WPMediaPicker
import Gutenberg
import MediaEditor
class GutenbergMediaInserterHelper: NSObject {
fileprivate let post: AbstractPost
fileprivate let gutenberg: Gutenberg
fileprivate let mediaCoordinator = MediaCoordinator.shared
fileprivate var mediaObserverReceipt: UUID?
/// Method of selecting media for upload, used for analytics
///
fileprivate var mediaSelectionMethod: MediaSelectionMethod = .none
var didPickMediaCallback: GutenbergMediaPickerHelperCallback?
init(post: AbstractPost, gutenberg: Gutenberg) {
self.post = post
self.gutenberg = gutenberg
super.init()
self.registerMediaObserver()
}
deinit {
self.unregisterMediaObserver()
}
func insertFromSiteMediaLibrary(media: [Media], callback: @escaping MediaPickerDidPickMediaCallback) {
let formattedMedia = media.map { item in
return MediaInfo(id: item.mediaID?.int32Value, url: item.remoteURL, type: item.mediaTypeString, caption: item.caption, title: item.filename, alt: item.alt)
}
callback(formattedMedia)
}
func insertFromDevice(assets: [PHAsset], callback: @escaping MediaPickerDidPickMediaCallback) {
guard (assets as [AsyncImage]).filter({ $0.isEdited }).isEmpty else {
insertFromMediaEditor(assets: assets, callback: callback)
return
}
var mediaCollection: [MediaInfo] = []
let group = DispatchGroup()
assets.forEach { asset in
group.enter()
insertFromDevice(asset: asset, callback: { media in
guard let media = media,
let selectedMedia = media.first else {
group.leave()
return
}
mediaCollection.append(selectedMedia)
group.leave()
})
}
group.notify(queue: .main) {
callback(mediaCollection)
}
}
func insertFromDevice(asset: PHAsset, callback: @escaping MediaPickerDidPickMediaCallback) {
guard let media = insert(exportableAsset: asset, source: .deviceLibrary) else {
callback([])
return
}
let options = PHImageRequestOptions()
options.deliveryMode = .fastFormat
options.version = .current
options.resizeMode = .fast
options.isNetworkAccessAllowed = true
let mediaUploadID = media.gutenbergUploadID
// Getting a quick thumbnail of the asset to display while the image is being exported and uploaded.
PHImageManager.default().requestImage(for: asset, targetSize: asset.pixelSize(), contentMode: .default, options: options) { (image, info) in
guard let thumbImage = image, let resizedImage = thumbImage.resizedImage(asset.pixelSize(), interpolationQuality: CGInterpolationQuality.low) else {
callback([MediaInfo(id: mediaUploadID, url: nil, type: media.mediaTypeString)])
return
}
let filePath = NSTemporaryDirectory() + "\(mediaUploadID).jpg"
let url = URL(fileURLWithPath: filePath)
do {
try resizedImage.writeJPEGToURL(url)
callback([MediaInfo(id: mediaUploadID, url: url.absoluteString, type: media.mediaTypeString)])
} catch {
callback([MediaInfo(id: mediaUploadID, url: nil, type: media.mediaTypeString)])
return
}
}
}
func insertFromDevice(url: URL, callback: @escaping MediaPickerDidPickMediaCallback) {
guard let media = insert(exportableAsset: url as NSURL, source: .otherApps) else {
callback([])
return
}
let mediaUploadID = media.gutenbergUploadID
callback([MediaInfo(id: mediaUploadID, url: url.absoluteString, type: media.mediaTypeString)])
}
func insertFromImage(image: UIImage, callback: @escaping MediaPickerDidPickMediaCallback, source: MediaSource = .deviceLibrary) {
guard let media = insert(exportableAsset: image, source: source) else {
callback([])
return
}
let mediaUploadID = media.gutenbergUploadID
let filePath = NSTemporaryDirectory() + "\(mediaUploadID).jpg"
let url = URL(fileURLWithPath: filePath)
do {
try image.writeJPEGToURL(url)
callback([MediaInfo(id: mediaUploadID, url: url.absoluteString, type: media.mediaTypeString)])
} catch {
callback([MediaInfo(id: mediaUploadID, url: nil, type: media.mediaTypeString)])
return
}
}
func insertFromMediaEditor(assets: [AsyncImage], callback: @escaping MediaPickerDidPickMediaCallback) {
var mediaCollection: [MediaInfo] = []
let group = DispatchGroup()
assets.forEach { asset in
group.enter()
if let image = asset.editedImage {
insertFromImage(image: image, callback: { media in
guard let media = media,
let selectedMedia = media.first else {
group.leave()
return
}
mediaCollection.append(selectedMedia)
group.leave()
})
} else if let asset = asset as? PHAsset {
insertFromDevice(asset: asset, callback: { media in
guard let media = media,
let selectedMedia = media.first else {
group.leave()
return
}
mediaCollection.append(selectedMedia)
group.leave()
})
}
}
group.notify(queue: .main) {
callback(mediaCollection)
}
}
func syncUploads() {
if mediaObserverReceipt != nil {
registerMediaObserver()
}
for media in post.media {
if media.remoteStatus == .failed {
gutenberg.mediaUploadUpdate(id: media.gutenbergUploadID, state: .uploading, progress: 0, url: media.absoluteThumbnailLocalURL, serverID: nil)
gutenberg.mediaUploadUpdate(id: media.gutenbergUploadID, state: .failed, progress: 0, url: nil, serverID: nil)
}
}
}
func mediaFor(uploadID: Int32) -> Media? {
for media in post.media {
if media.gutenbergUploadID == uploadID {
return media
}
}
return nil
}
func isUploadingMedia() -> Bool {
return mediaCoordinator.isUploadingMedia(for: post)
}
func cancelUploadOfAllMedia() {
mediaCoordinator.cancelUploadOfAllMedia(for: post)
}
func cancelUploadOf(media: Media) {
mediaCoordinator.cancelUploadAndDeleteMedia(media)
gutenberg.mediaUploadUpdate(id: media.gutenbergUploadID, state: .reset, progress: 0, url: nil, serverID: nil)
}
func retryUploadOf(media: Media) {
mediaCoordinator.retryMedia(media)
}
func hasFailedMedia() -> Bool {
return mediaCoordinator.hasFailedMedia(for: post)
}
func insert(exportableAsset: ExportableAsset, source: MediaSource) -> Media? {
let info = MediaAnalyticsInfo(origin: .editor(source), selectionMethod: mediaSelectionMethod)
return mediaCoordinator.addMedia(from: exportableAsset, to: self.post, analyticsInfo: info)
}
/// Method to be used to refresh the status of all media associated with the post.
/// this method should be called when opening a post to make sure every media block has the correct visual status.
func refreshMediaStatus() {
for media in post.media {
switch media.remoteStatus {
case .processing:
mediaObserver(media: media, state: .processing)
case .pushing:
var progressValue = 0.5
if let progress = mediaCoordinator.progress(for: media) {
progressValue = progress.fractionCompleted
}
mediaObserver(media: media, state: .progress(value: progressValue))
case .failed:
if let error = media.error as NSError? {
mediaObserver(media: media, state: .failed(error: error))
}
default:
break
}
}
}
private func registerMediaObserver() {
mediaObserverReceipt = mediaCoordinator.addObserver({ [weak self](media, state) in
self?.mediaObserver(media: media, state: state)
}, forMediaFor: post)
}
private func unregisterMediaObserver() {
if let receipt = mediaObserverReceipt {
mediaCoordinator.removeObserver(withUUID: receipt)
}
}
private func mediaObserver(media: Media, state: MediaCoordinator.MediaState) {
let mediaUploadID = media.gutenbergUploadID
switch state {
case .processing:
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .uploading, progress: 0, url: nil, serverID: nil)
case .thumbnailReady(let url):
guard ReachabilityUtils.isInternetReachable() && media.remoteStatus != .failed else {
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .failed, progress: 0, url: url, serverID: nil)
return
}
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .uploading, progress: 0.20, url: url, serverID: nil)
break
case .uploading:
break
case .ended:
var currentURL = media.remoteURL
if media.remoteLargeURL != nil {
currentURL = media.remoteLargeURL
} else if media.remoteMediumURL != nil {
currentURL = media.remoteMediumURL
}
guard let urlString = currentURL, let url = URL(string: urlString), let mediaServerID = media.mediaID?.int32Value else {
break
}
switch media.mediaType {
case .video:
EditorMediaUtility.fetchRemoteVideoURL(for: media, in: post) { [weak self] (result) in
guard let strongSelf = self else {
return
}
switch result {
case .failure:
strongSelf.gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .failed, progress: 0, url: nil, serverID: nil)
case .success(let value):
strongSelf.gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .succeeded, progress: 1, url: value.videoURL, serverID: mediaServerID)
}
}
default:
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .succeeded, progress: 1, url: url, serverID: mediaServerID)
}
case .failed(let error):
if error.code == NSURLErrorCancelled {
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .reset, progress: 0, url: nil, serverID: nil)
return
}
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .failed, progress: 0, url: nil, serverID: nil)
case .progress(let value):
gutenberg.mediaUploadUpdate(id: mediaUploadID, state: .uploading, progress: Float(value), url: nil, serverID: nil)
}
}
}
extension Media {
var gutenbergUploadID: Int32 {
return Int32(truncatingIfNeeded: objectID.uriRepresentation().absoluteString.hash)
}
}
| gpl-2.0 | 09f7eb77926d550d49192856e3e5b783 | 39.116438 | 167 | 0.600478 | 4.872712 | false | false | false | false |
Ahyufei/DouYuTV | DYTV/DYTV/Classes/Main/Controller/BaseAnchorViewController.swift | 1 | 4812 | //
// BaseAnchorViewController.swift
// DYTV
//
// Created by Yufei on 2017/1/17.
// Copyright © 2017年 张玉飞. All rights reserved.
//
import UIKit
fileprivate let kNomalCellID = "kNomalCellID"
fileprivate let kPrettyCellID = "kPrettyCellID"
fileprivate let kHeaderSectionID = "kHeaderSectionID"
fileprivate let kItemMargin : CGFloat = 10
fileprivate let kHeaderSectionH : CGFloat = 50
fileprivate let kItemW = (kScreenW - kItemMargin * 3) / 2
fileprivate let kNomalItemH = kItemW * 3 / 4
fileprivate let kPrettyItemH = kItemW * 4 / 3
fileprivate let kCycleViewH = kScreenW * 3 / 8
fileprivate let kGameViewH : CGFloat = 90
class BaseAnchorViewController: BaseViewController {
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = { [unowned self] in
// 创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNomalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderSectionH)
// 内边距
layout.sectionInset = UIEdgeInsetsMake(0, kItemMargin, 0, kItemMargin)
// 创建collectionView
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
// 注册
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: kNomalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderSectionID)
return collectionView
}()
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK:- 设置UI
extension BaseAnchorViewController {
override func setupUI() {
contentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
}
// MARK:- 请求数据
extension BaseAnchorViewController {
func loadData() {
}
}
// MARK:- UICollectionViewDataSource
extension BaseAnchorViewController : UICollectionViewDataSource{
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNomalCellID, for: indexPath) as! CollectionNormalCell
// cell.backgroundColor = UIColor.randomColor()
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let headerSectionView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderSectionID, for: indexPath) as! CollectionHeaderView
headerSectionView.group = baseVM.anchorGroups[indexPath.section]
return headerSectionView
}
}
// MARK:- UICollectionViewDelegate
extension BaseAnchorViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 取出主播信息
let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc()
}
private func presentShowRoomVc() {
// 1.创建ShowRoomVc
let showRoomVc = RoomShowViewController()
// 2.以Modal方式弹出
present(showRoomVc, animated: true, completion: nil)
}
private func pushNormalRoomVc() {
// 1.创建NormalRoomVc
let normalRoomVc = RoomNormalViewController()
// 2.以Push方式弹出
navigationController?.pushViewController(normalRoomVc, animated: true)
}
}
| mit | 52798b5b8a2b4da6ed36267a64110497 | 33.807407 | 189 | 0.700787 | 5.661446 | false | false | false | false |
planvine/Line-Up-iOS-SDK | Pod/Classes/Utilities/Constants.swift | 1 | 5110 | //
// Constants.swift
// Pods
//
// Created by Andrea Ferrando on 04/02/2016.
//
//
import Foundation
import CoreData
public var kApiKey: String!
public var kApiBase: String!
public var kStripePublishableKey: String!
struct PVConfig {
static let apiBase = kApiBase
static let stripePublishableKey = kStripePublishableKey
static let attachApiKey = "apiKey=\(kApiKey)"
static let attachAuthorization = "Authorization=%@"
static let attachHasTickets = "hasTickets=1"
static let bundle = "ResourceBundle.bundle"
static var merchantId = ""
}
struct PVEntity {
static let PVEvent = "PVEvent"
static let PVVenue = "PVVenue"
static let PVPerformance = "PVPerformance"
static let PVTicket = "PVTicket"
static let PVReceipt = "PVReceipt"
static let PVCard = "PVCard"
static let PVUser = "PVUser"
}
struct PVMetric {
static let padTiny : CGFloat = 5
static let padSmall : CGFloat = 10
static let padMedium : CGFloat = 15
static let padBig : CGFloat = 20
static let padHuge : CGFloat = 25
static func pads() -> Dictionary<String,CGFloat>{
return Dictionary(dictionaryLiteral:("padTiny",padTiny),("padSmall",padSmall),("padMedium",padMedium),("padBig",padBig),("padHuge",padHuge))
}
}
struct PVConstant {
static let barHeight: CGFloat = 64
static let toolbarHeight: CGFloat = 44
static let pageControllerCardHeight: CGFloat = 70
static let maxNumberOfTicketsPerPerformance: NSNumber = 6
static let totalViewListOfTicketsHeight: CGFloat = 30
}
struct PVError {
internal static let timeOutTime: Double = 7.0
static let alertUser_generalError = "There was a problem placing the order. Please try again or contact us for help"
static let alertUser_ReservationExpired = "Reservation expired. Your time ran out, please try ordering again"
static let alertUser_ReservationProcessError = "An error occured with reserving tickets. Please try again"
static let alertUser_UserAlreadySignedUp = "A user is already signed up with this email address or the email address is not valid. Please try again or contact us for help"
static let alertUser_EmailAddressNotValid = "This email address isn’t recognised. Please review the email address and ensure that it is correct"
static let alertUser_ChangeDefaultCard = "Payment failed. Please add a new payment card or try an alternative payment method"
static let alertUser_NewCardEmailNotValid = "This email address isn’t recognised. Please review the email address and ensure that it is correct"
static let alertUser_EmailAddressChangeFailed = "Payment failed. Email address incorrect or it already exists with another account"
static let alertUser_NewCardNotValid = "Error creating the new card"
static let alertUser_EmailAndTokenNotMatching = "There was a problem placing the order. Your email address already exists. Please contact us for help"
static let alertUser_SetDefaultCardError = "An error occured with the credit card. Please try again or contact us for help"
static let alertUser_StripeToken = "There has been a problem with your order. Please try again or contact us for help"
static let alertUser_PaymentFailed = "There was a problem placing the order. Please try again or contact us for help"
static let alertDeveloper_ReservationExpired = "Reservation timeout. Try again"
static let alertDeveloper_ReservationProcessError = "Error with reservation, it may be expired"
static let alertDeveloper_UserAlreadySignedUp = "This user is already signed up or the email address is not valid. Try again sending the userToken"
static let alertDeveloper_EmailAddressNotValid = "Error - not valid email address"
static let alertDeveloper_ChangeDefaultCard = "Payment failed. Try alternative payent method"
static let alertDeveloper_JSONCreation = "Error creating the jSON file to POST"
static let alertDeveloper_EmailAddressChangeFailed = "Error changing the deafult user email address, maybe the email address already exists with another account"
static let alertDeveloper_EmailAndTokenNotMatching = "User email and user token don't match."
static let alertDeveloper_DelegateNotFound = "Have you set the delegate for LineUpDelegate?"
static let alertDeveloper_NewCardNotValid = "Error creating the new card"
static let alertDeveloper_NewCardEmailNotValid = "This email address isn’t recognised. Please review the email address and ensure that it is correct"
static let alertDeveloper_SetDefaultCardError = "Error setting the default card"
static let alertDeveloper_StripeToken = "Error posting the Stripe Token to LineUp"
static let alertDeveloper_PaymentFailed = "You need to provide a credit card or a userToken"
static let alert_ApplePayNotAvailable = "It is not possible to use ApplePay. Pay by credit card"
static let alertTimeout = "The request timed out"
static let alertNoConnection = "You have no internet connection available. Please connect to a WIFI network or mobile internet for purchasing tickets"
}
| mit | bb6944e1a586865e202305527c8209eb | 53.297872 | 175 | 0.76156 | 4.536889 | false | false | false | false |
caopengxu/scw | scw/Pods/Moya/Sources/Moya/MoyaProvider.swift | 3 | 7403 | import Foundation
import Result
/// Closure to be executed when a request has completed.
public typealias Completion = (_ result: Result<Moya.Response, MoyaError>) -> Void
/// Closure to be executed when progress changes.
public typealias ProgressBlock = (_ progress: ProgressResponse) -> Void
public struct ProgressResponse {
public let response: Response?
public let progressObject: Progress?
public init(progress: Progress? = nil, response: Response? = nil) {
self.progressObject = progress
self.response = response
}
public var progress: Double {
return progressObject?.fractionCompleted ?? 1.0
}
public var completed: Bool {
return progress == 1.0 && response != nil
}
}
public protocol MoyaProviderType: class {
associatedtype Target: TargetType
func request(_ target: Target, callbackQueue: DispatchQueue?, progress: Moya.ProgressBlock?, completion: @escaping Moya.Completion) -> Cancellable
}
/// Request provider class. Requests should be made through this class only.
open class MoyaProvider<Target: TargetType>: MoyaProviderType {
/// Closure that defines the endpoints for the provider.
public typealias EndpointClosure = (Target) -> Endpoint<Target>
/// Closure that decides if and what request should be performed
public typealias RequestResultClosure = (Result<URLRequest, MoyaError>) -> Void
/// Closure that resolves an `Endpoint` into a `RequestResult`.
public typealias RequestClosure = (Endpoint<Target>, @escaping RequestResultClosure) -> Void
/// Closure that decides if/how a request should be stubbed.
public typealias StubClosure = (Target) -> Moya.StubBehavior
open let endpointClosure: EndpointClosure
open let requestClosure: RequestClosure
open let stubClosure: StubClosure
open let manager: Manager
/// A list of plugins
/// e.g. for logging, network activity indicator or credentials
open let plugins: [PluginType]
open let trackInflights: Bool
open internal(set) var inflightRequests: [Endpoint<Target>: [Moya.Completion]] = [:]
/// Propagated to Alamofire as callback queue. If nil - the Alamofire default (as of their API in 2017 - the main queue) will be used.
let callbackQueue: DispatchQueue?
/// Initializes a provider.
public init(endpointClosure: @escaping EndpointClosure = MoyaProvider.defaultEndpointMapping,
requestClosure: @escaping RequestClosure = MoyaProvider.defaultRequestMapping,
stubClosure: @escaping StubClosure = MoyaProvider.neverStub,
callbackQueue: DispatchQueue? = nil,
manager: Manager = MoyaProvider<Target>.defaultAlamofireManager(),
plugins: [PluginType] = [],
trackInflights: Bool = false) {
self.endpointClosure = endpointClosure
self.requestClosure = requestClosure
self.stubClosure = stubClosure
self.manager = manager
self.plugins = plugins
self.trackInflights = trackInflights
self.callbackQueue = callbackQueue
}
/// Returns an `Endpoint` based on the token, method, and parameters by invoking the `endpointClosure`.
open func endpoint(_ token: Target) -> Endpoint<Target> {
return endpointClosure(token)
}
/// Designated request-making method. Returns a `Cancellable` token to cancel the request later.
@discardableResult
open func request(_ target: Target,
callbackQueue: DispatchQueue? = .none,
progress: ProgressBlock? = .none,
completion: @escaping Completion) -> Cancellable {
let callbackQueue = callbackQueue ?? self.callbackQueue
return requestNormal(target, callbackQueue: callbackQueue, progress: progress, completion: completion)
}
/// When overriding this method, take care to `notifyPluginsOfImpendingStub` and to perform the stub using the `createStubFunction` method.
/// Note: this was previously in an extension, however it must be in the original class declaration to allow subclasses to override.
@discardableResult
open func stubRequest(_ target: Target, request: URLRequest, callbackQueue: DispatchQueue?, completion: @escaping Moya.Completion, endpoint: Endpoint<Target>, stubBehavior: Moya.StubBehavior) -> CancellableToken {
let callbackQueue = callbackQueue ?? self.callbackQueue
let cancellableToken = CancellableToken { }
notifyPluginsOfImpendingStub(for: request, target: target)
let plugins = self.plugins
let stub: () -> Void = createStubFunction(cancellableToken, forTarget: target, withCompletion: completion, endpoint: endpoint, plugins: plugins, request: request)
switch stubBehavior {
case .immediate:
switch callbackQueue {
case .none:
stub()
case .some(let callbackQueue):
callbackQueue.async(execute: stub)
}
case .delayed(let delay):
let killTimeOffset = Int64(CDouble(delay) * CDouble(NSEC_PER_SEC))
let killTime = DispatchTime.now() + Double(killTimeOffset) / Double(NSEC_PER_SEC)
(callbackQueue ?? DispatchQueue.main).asyncAfter(deadline: killTime) {
stub()
}
case .never:
fatalError("Method called to stub request when stubbing is disabled.")
}
return cancellableToken
}
}
/// Mark: Stubbing
/// Controls how stub responses are returned.
public enum StubBehavior {
/// Do not stub.
case never
/// Return a response immediately.
case immediate
/// Return a response after a delay.
case delayed(seconds: TimeInterval)
}
public extension MoyaProvider {
// Swift won't let us put the StubBehavior enum inside the provider class, so we'll
// at least add some class functions to allow easy access to common stubbing closures.
public final class func neverStub(_: Target) -> Moya.StubBehavior {
return .never
}
public final class func immediatelyStub(_: Target) -> Moya.StubBehavior {
return .immediate
}
public final class func delayedStub(_ seconds: TimeInterval) -> (Target) -> Moya.StubBehavior {
return { _ in return .delayed(seconds: seconds) }
}
}
public func convertResponseToResult(_ response: HTTPURLResponse?, request: URLRequest?, data: Data?, error: Swift.Error?) ->
Result<Moya.Response, MoyaError> {
switch (response, data, error) {
case let (.some(response), data, .none):
let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response)
return .success(response)
case let (.some(response), _, .some(error)):
let response = Moya.Response(statusCode: response.statusCode, data: data ?? Data(), request: request, response: response)
let error = MoyaError.underlying(error, response)
return .failure(error)
case let (_, _, .some(error)):
let error = MoyaError.underlying(error, nil)
return .failure(error)
default:
let error = MoyaError.underlying(NSError(domain: NSURLErrorDomain, code: NSURLErrorUnknown, userInfo: nil), nil)
return .failure(error)
}
}
| mit | 1c3d113a0caaed6388362c4bad041e0e | 40.127778 | 217 | 0.676212 | 5.173305 | false | false | false | false |
sprejjs/MeMe | MeMe/MeMe/View Controllers/SentImagesCollectionViewController.swift | 1 | 2112 | //
// Created by Vlad Spreys on 8/03/15.
// Copyright (c) 2015 Spreys.com. All rights reserved.
//
import UIKit
import Foundation
class SentImagesCollectionViewController : UICollectionViewController {
var memes : [Meme]!
@IBAction func newMeme(sender: UIBarButtonItem) {
self.dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Sent Memes"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
let object = UIApplication.sharedApplication().delegate
let appDelegate = object as! AppDelegate
self.memes = appDelegate.memes
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("MemeCell", forIndexPath: indexPath) as! SentMemesCollectionViewCell
let meme = self.memes[indexPath.item]
cell.imageView?.image = meme.memedImage
return cell;
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.memes.count
}
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let detailViewController = self.storyboard!.instantiateViewControllerWithIdentifier("MemeDetailViewController") as! MemeDetailViewController
//The line below is a hack to instantiate outlets. Without it imageView is nil.
//Refer to http://stackoverflow.com/questions/12523198/storyboard-instantiateviewcontrollerwithidentifier-not-setting-iboutlets for details
print(detailViewController.view)
detailViewController.imageView.image = self.memes[indexPath.item].memedImage
self.navigationController!.pushViewController(detailViewController, animated: true)
}
}
| mit | c8b4822da2ea23b095d5463ab5b1a410 | 37.4 | 148 | 0.708807 | 5.834254 | false | false | false | false |
ainame/Swift-WebP | iOS Example/Sources/ViewController.swift | 1 | 1730 | //
// ViewController.swift
// iOS Example
//
// Created by ainame on Jan 32, 2032.
// Copyright © 2016 satoshi.namai. All rights reserved.
//
import UIKit
import WebP
import CoreGraphics
class IOSViewController: UIViewController {
enum State {
case none
case processing
}
@IBOutlet weak var convertButton: UIButton!
@IBOutlet weak var beforeImageView: UIImageView!
@IBOutlet weak var afterImageView: UIImageView!
var state: State = .none
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func didTapButton(_ sender: Any) {
print("tapped")
if state == .processing { return }
state = .processing
let encoder = WebPEncoder()
let decoder = WebPDecoder()
let queue = DispatchQueue(label: "me.ainam.webp")
let image = beforeImageView.image!
queue.async {
do {
print("convert start")
let data = try! encoder.encode(image, config: .preset(.picture, quality: 95))
var options = WebPDecoderOptions()
options.scaledWidth = Int(image.size.width)
options.scaledHeight = Int(image.size.height)
let webpImage = try decoder.decode(toUImage: data, options: options)
print("decode finish")
DispatchQueue.main.async {
self.afterImageView.image = webpImage
self.state = .none
}
} catch let error {
self.state = .none
print(error)
}
}
}
}
| mit | 2dfb215d6b1b1b8be1c815e6a2df29a6 | 27.344262 | 93 | 0.567958 | 4.69837 | false | false | false | false |
brettchien/SwiftBLEWrapper | EPLCentralManager.swift | 1 | 7224 | //
// EPLCentralManager.swift
// SSBLE
//
// Created by Ting-Chou Chien on 1/15/15.
// Copyright (c) 2015 Ting-Chou Chien. All rights reserved.
//
import Foundation
import CoreBluetooth
import XCGLogger
//import Async
// MARK: -
// MARK: EPLCentralManagerDelegate Protocol
@objc public protocol EPLCentralManagerDelegate {
// required functions
func afterBLEIsReady(central: EPLCentralManager!)
func didDiscoverPeripherals(central: EPLCentralManager!)
func didConnectedPeripheral(peripheral: EPLPeripheral!)
func didDisconnectedPeripheral(peripheral: EPLPeripheral!)
// optional functions
optional func afterScanTimeout(central: EPLCentralManager!)
}
// MARK: -
// MARK: EPLCentralManager Class
public class EPLCentralManager: NSObject, CBCentralManagerDelegate {
// MARK: -
// MARK: Private variables
private let log = XCGLogger.defaultInstance()
private var cbCentralManager: CBCentralManager
private let centralQueue = dispatch_queue_create("epl.ble.central.main", DISPATCH_QUEUE_SERIAL)
private var _ble_ready: Bool = false
private var scanOption:Dictionary<String, AnyObject> = [:]
private var block = Async.background {}
// MARK: -
// MARK: Internal variables
// MARK: -
// MARK: Public variables
// singleton, there's only one EPLCentralManager for the whole system
public class var sharedInstance: EPLCentralManager {
struct Static {
static let instance = EPLCentralManager()
}
return Static.instance
}
public var ble_ready: Bool {
get {
return self._ble_ready
}
set {
self._ble_ready = newValue
if self._ble_ready == true {
delegate?.afterBLEIsReady(self)
}
}
}
public var delegate: EPLCentralManagerDelegate?
public var connectedPeripherals: [CBPeripheral :EPLPeripheral] = [:]
public var discoveredPeripherals: [CBPeripheral : EPLPeripheral] = [:]
// MARK: -
// MARK: Private Interface
// MARK: -
// MARK: Internal Interface
// MARK: -
// MARK: Public Interface
public override init() {
cbCentralManager = CBCentralManager()
super.init()
self.cbCentralManager = CBCentralManager(delegate: self, queue: self.centralQueue)
}
public func reset() {
self.cbCentralManager = CBCentralManager(delegate: self, queue: self.centralQueue)
}
public func scan(timeout: Double = 10.0, allowDuplicated: Bool = false) {
self.log.debug("Start Scanning for peripherals")
// insert a background delay then rise a timeout event
self.block = Async.background(after: timeout) {
self.log.debug("Scan Timeout")
self.stopScan()
self.delegate?.afterScanTimeout!(self)
}
self.scanOption[CBCentralManagerScanOptionAllowDuplicatesKey] = allowDuplicated
self.scanOption[CBCentralManagerScanOptionSolicitedServiceUUIDsKey] = []
self.cbCentralManager.scanForPeripheralsWithServices(nil, options: self.scanOption)
}
public func stopScan() {
self.log.debug("Stop scanning")
self.cbCentralManager.stopScan()
}
public func connect(peripheral: EPLPeripheral, options: [String: AnyObject]! = nil) {
self.log.debug("Connect to \(peripheral.name)")
self.cbCentralManager.connectPeripheral(peripheral.cbPeripheral, options: options)
}
public func disconnect(peripheral: EPLPeripheral) {
self.log.debug("Disconnect with \(peripheral.name)")
self.cbCentralManager.cancelPeripheralConnection(peripheral.cbPeripheral)
}
}
extension EPLCentralManager {
// MARK: -
// MARK: Monitoring Connections with Peripherals
public func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
self.log.debug("didConnect")
Async.main {
print(peripheral)
let ep = EPLPeripheral(cbPeripheral: peripheral)
self.discoveredPeripherals.removeValueForKey(peripheral)
self.connectedPeripherals[peripheral] = ep
if let d = self.delegate {
d.didConnectedPeripheral(ep)
}
}
}
public func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
if let err = error {
self.log.error("Disconnect with Error: \(err)")
}
let p = peripheral
let ep = EPLPeripheral(cbPeripheral: p)
self.connectedPeripherals.removeValueForKey(p)
self.delegate?.didDisconnectedPeripheral(ep)
}
public func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
self.log.error("didFailToConnectPeripheral")
let p = peripheral
var ep = EPLPeripheral(cbPeripheral: p)
self.discoveredPeripherals.removeValueForKey(p)
self.connectedPeripherals.removeValueForKey(p)
}
// MARK: -
// MARK: Discovering and Retrieving Peripherals
public func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
let rssi = RSSI
var ep = EPLPeripheral(cbPeripheral: peripheral, advData: advertisementData)
self.discoveredPeripherals[peripheral] = ep
self.log.debug("didDiscover \(peripheral)")
self.delegate?.didDiscoverPeripherals(self)
}
// MARK: -
// MARK: Monitoring Changes to the Central Manager's State
public func centralManagerDidUpdateState(central: CBCentralManager) {
self.ble_ready = false
self.cbCentralManager = central
switch self.cbCentralManager.state {
case .Unauthorized:
break
case .Unknown:
break
case .Unsupported:
break
case .PoweredOff:
break
case .PoweredOn:
self.ble_ready = true
case .Resetting:
break
}
}
public func centralManager(central: CBCentralManager, willRestoreState dict: [String : AnyObject]) {
}
// deprecated
// public func centralManager(central: CBCentralManager!, didRetrieveConnectedPeripherals peripherals: [AnyObject]!) {
// self.log.debug("didRetrieveConnected")
// if let ps = peripherals {
// for p in ps {
// let p = p as! CBPeripheral
// var ep = EPLPeripheral(cbPeripheral: p)
// self.connectedPeripherals[p] = ep
// }
// }
// }
//
// public func centralManager(central: CBCentralManager!, didRetrievePeripherals peripherals: [AnyObject]!) {
// print("didRetrieve")
// if let ps = peripherals {
// for p in ps {
// let p = p as! CBPeripheral
// var ep = EPLPeripheral(cbPeripheral: p)
// self.discoveredPeripherals[p] = ep
// }
// }
// }
}
| mit | e35f0f2a71662fb99264b20f3e54c9af | 33.4 | 164 | 0.641196 | 4.904277 | false | false | false | false |
ethanneff/organize | Organize/ListViewController.swift | 1 | 29697 | import UIKit
import MessageUI
import Firebase
import GoogleMobileAds
class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, MFMailComposeViewControllerDelegate, ListTableViewCellDelegate, SettingsDelegate, ReorderTableViewDelegate,GADBannerViewDelegate {
// MARK: - properties
private var notebook: Notebook
lazy var tableView: UITableView = ReorderTableView()
weak var menuDelegate: MenuViewController?
private var addButton: UIButton!
private var bannerAd: GADBannerView!
private var bannerAdHeight: CGFloat = 50
private var tableViewBottomConstraint: NSLayoutConstraint!
private var addButtonBottomPadding: CGFloat = Constant.Button.padding*2
private var addButtonBottomConstraint: NSLayoutConstraint!
lazy var refreshControl: UIRefreshControl = {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(tableViewRefresh(_:)), forControlEvents: UIControlEvents.ValueChanged)
refreshControl.tintColor = Constant.Color.title.colorWithAlphaComponent(0.5)
return refreshControl
}()
// MARK: - init
init() {
notebook = Notebook(title: "")
super.init(nibName: nil, bundle: nil)
initialize()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init coder not implemented")
}
private func initialize() {
loadNotebook()
loadListeners()
createBannerAd()
createTableView()
createAddButton()
createGestures()
}
// MARK: - deinit
deinit {
print("list deinit)")
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillTerminateNotification, object: nil)
// FIXME: dismiss viewcontollor does not call deinit (reference cycle) (has to do with menu)
}
// MARK: - error
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - appear
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
// session
loadSession()
// config
loadRemoteConfig()
// title
updateTitle()
// accessed
Remote.User.open()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// shake
becomeFirstResponder()
}
// MARK: - load
internal func applicationDidBecomeActiveNotification() {
// update reminder icons
tableView.reloadData()
}
internal func applicationDidBecomeInactiveNotification() {
Remote.Auth.upload(notebook: notebook)
}
private func loadNotebook() {
Notebook.get { data in
if let data = data {
Util.threadMain {
self.notebook = data
self.tableView.reloadData()
self.updateTitle()
}
} else {
self.displayLogout()
}
}
}
private func loadListeners() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationDidBecomeActiveNotification), name: UIApplicationDidBecomeActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationDidBecomeInactiveNotification), name: UIApplicationWillResignActiveNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationDidBecomeInactiveNotification), name: UIApplicationWillTerminateNotification, object: nil)
}
private func loadSession() {
let reviewCount = Constant.UserDefault.get(key: Constant.UserDefault.Key.ReviewCount) as? Int ?? 0
Constant.UserDefault.set(key: Constant.UserDefault.Key.ReviewCount, val: reviewCount+1)
}
private func loadRemoteConfig() {
Remote.Config.fetch { config in
if let config = config {
// ads
if let user = Remote.Auth.user {
// FIXME: remove hardcode in place for user check if paid
if user.email != "[email protected]" && config[Remote.Config.Keys.ShowAds.rawValue].boolValue {
self.loadBannerAd()
}
}
// review
let feedbackApp = Constant.UserDefault.get(key: Constant.UserDefault.Key.FeedbackApp) as? Bool ?? false
let reviewApp = Constant.UserDefault.get(key: Constant.UserDefault.Key.ReviewApp) as? Bool ?? false
let reviewCount = Constant.UserDefault.get(key: Constant.UserDefault.Key.ReviewCount) as? Int ?? 0
let reviewCountConfig = config[Remote.Config.Keys.ShowReview.rawValue].numberValue as? Int ?? 0
if !(reviewApp || feedbackApp) && reviewCount > reviewCountConfig {
self.displayReview()
}
}
}
}
// MARK: - create
private func createBannerAd() {
bannerAd = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
view.addSubview(bannerAd)
bannerAd.delegate = self
bannerAd.rootViewController = self
bannerAd.adUnitID = Constant.App.firebaseBannerAdUnitID
bannerAd.translatesAutoresizingMaskIntoConstraints = false
bannerAd.backgroundColor = Constant.Color.background
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: bannerAd, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: bannerAdHeight),
NSLayoutConstraint(item: bannerAd, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: bannerAd, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0),
NSLayoutConstraint(item: bannerAd, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0),
])
}
private func createTableView() {
// add
view.addSubview(tableView)
// delegates
tableView.delegate = self
tableView.dataSource = self
if let tableView = tableView as? ReorderTableView {
tableView.reorderDelegate = self
}
// cell
tableView.registerClass(ListTableViewCell.self, forCellReuseIdentifier: ListTableViewCell.identifier)
// refresh
tableView.addSubview(refreshControl)
// color
tableView.backgroundColor = Constant.Color.background
// borders
tableView.contentInset = UIEdgeInsetsZero
tableView.separatorInset = UIEdgeInsetsZero
tableView.separatorColor = Constant.Color.border
tableView.scrollIndicatorInsets = UIEdgeInsetsZero
tableView.tableFooterView = UIView(frame: CGRect.zero)
if #available(iOS 9.0, *) {
tableView.cellLayoutMarginsFollowReadableWidth = false
}
tableView.layoutMargins = UIEdgeInsetsZero
// constraints
tableView.translatesAutoresizingMaskIntoConstraints = false
tableViewBottomConstraint = NSLayoutConstraint(item: tableView, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: 0)
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: tableView, attribute: .Top, relatedBy: .Equal, toItem: view, attribute: .Top, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: .Leading, relatedBy: .Equal, toItem: view, attribute: .Leading, multiplier: 1, constant: 0),
NSLayoutConstraint(item: tableView, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: 0),
tableViewBottomConstraint,
])
}
private func createAddButton() {
let button = UIButton()
let buttonSize = Constant.Button.height*1.33
let image = UIImage(named: "icon-add")!
let imageView = Util.imageViewWithColor(image: image, color: Constant.Color.background)
view.addSubview(button)
button.layer.cornerRadius = buttonSize/2
// TODO: make shadow same as menu
button.layer.shadowColor = UIColor.blackColor().CGColor
button.layer.shadowOffset = CGSizeMake(0, 2)
button.layer.shadowOpacity = 0.2
button.layer.shadowRadius = 2
button.layer.masksToBounds = false
button.backgroundColor = Constant.Color.button
button.tintColor = Constant.Color.background
button.setImage(imageView.image, forState: .Normal)
button.setImage(imageView.image, forState: .Highlighted)
button.addTarget(self, action: #selector(addButtonPressed(_:)), forControlEvents: .TouchUpInside)
addButtonBottomConstraint = NSLayoutConstraint(item: button, attribute: .Bottom, relatedBy: .Equal, toItem: view, attribute: .Bottom, multiplier: 1, constant: -addButtonBottomPadding)
button.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activateConstraints([
NSLayoutConstraint(item: button, attribute: .Trailing, relatedBy: .Equal, toItem: view, attribute: .Trailing, multiplier: 1, constant: -addButtonBottomPadding),
addButtonBottomConstraint,
NSLayoutConstraint(item: button, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: buttonSize),
NSLayoutConstraint(item: button, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1, constant: buttonSize),
])
addButton = button
}
private func createGestures() {
// double tap
let gestureDoubleTap = UITapGestureRecognizer(target: self, action: #selector(gestureRecognizedDoubleTap(_:)))
gestureDoubleTap.numberOfTapsRequired = 2
gestureDoubleTap.numberOfTouchesRequired = 1
tableView.addGestureRecognizer(gestureDoubleTap)
// single tap
let gestureSingleTap = UITapGestureRecognizer(target: self, action: #selector(gestureRecognizedSingleTap(_:)))
gestureSingleTap.numberOfTapsRequired = 1
gestureSingleTap.numberOfTouchesRequired = 1
gestureSingleTap.requireGestureRecognizerToFail(gestureDoubleTap)
tableView.addGestureRecognizer(gestureSingleTap)
}
private func updateTitle() {
if let controller = self.navigationController?.childViewControllers.first {
controller.navigationItem.title = notebook.title
}
}
// MARK: - banner
private func loadBannerAd() {
let request = GADRequest()
request.testDevices = Constant.App.firebaseTestDevices
bannerAd.loadRequest(request)
}
internal func adViewDidReceiveAd(bannerView: GADBannerView!) {
displayBannerAd(show: true)
}
internal func adView(bannerView: GADBannerView!, didFailToReceiveAdWithError error: GADRequestError!) {
Report.sharedInstance.log("adView:didFailToReceiveAdWithError: \(error.localizedDescription)")
}
private func displayBannerAd(show show: Bool) {
tableViewBottomConstraint.constant = show ? -bannerAdHeight : 0
addButtonBottomConstraint.constant = show ? -bannerAdHeight-addButtonBottomPadding : 0
UIView.animateWithDuration(0.3, animations: {
self.view.layoutIfNeeded()
})
}
// MARK: - tableview datasource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
addButton?.hidden = notebook.display.count > 0
return notebook.display.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return ListTableViewCell.height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(ListTableViewCell.identifier, forIndexPath: indexPath) as! ListTableViewCell
cell.delegate = self
cell.updateCell(note: notebook.display[indexPath.row])
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// fixes separator disappearing
tableView.deselectRowAtIndexPath(indexPath, animated: false)
tableView.separatorStyle = .None;
tableView.separatorStyle = .SingleLine
}
// MARK: - refresh
func tableViewRefresh(refreshControl: UIRefreshControl) {
if !Constant.App.release {
notebook = Notebook.getDefault()
// notebook.display = notebook.notes
refreshControl.endRefreshing()
tableView.reloadData()
return
}
let modal = ModalConfirmation()
modal.trackButtons = true
modal.message = "Download from cloud and overwrite data on device?"
modal.show(controller: self, dismissible: true) { (output) in
refreshControl.endRefreshing()
if let selection = output[ModalConfirmation.OutputKeys.Selection.rawValue] as? Int where selection == 1 {
Remote.Auth.download(controller: self) { (error) in
if let error = error {
let modal = ModalError()
modal.message = error
modal.show(controller: self)
return
}
self.loadNotebook()
}
}
}
}
// MARK - swipe
func cellSwiped(type type: SwipeType, cell: UITableViewCell) {
Util.playSound(systemSound: .Tap)
if let indexPath = tableView.indexPathForCell(cell) {
switch type {
case .Complete: notebook.complete(indexPath: indexPath, tableView: tableView)
case .Indent: notebook.indent(indexPath: indexPath, tableView: tableView)
case .Reminder: displayReminder(indexPath: indexPath)
case .Uncomplete: notebook.uncomplete(indexPath: indexPath, tableView: tableView)
case .Unindent: notebook.unindent(indexPath: indexPath, tableView: tableView)
case .Delete: displayDeleteCell(indexPath: indexPath)
}
}
}
// MARK: - reorder
func reorderBeforeLift(fromIndexPath: NSIndexPath, completion: () -> ()) {
notebook.reorderBeforeLift(indexPath: fromIndexPath, tableView: tableView) {
completion()
}
Util.playSound(systemSound: .Tap)
}
func reorderAfterLift(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath, completion: () -> ()) {
notebook.reorderAfterLift(fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) {
completion()
}
}
func reorderDuringMove(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath, completion: () -> ()) {
notebook.reorderDuringMove(fromIndexPath: fromIndexPath, toIndexPath: toIndexPath) {
completion()
}
}
func reorderAfterDrop(fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath, completion: () -> ()) {
notebook.reorderAfterDrop(fromIndexPath: fromIndexPath, toIndexPath: toIndexPath, tableView: tableView) {
completion()
}
Util.playSound(systemSound: .Tap)
}
// MARK: - gestures
func gestureRecognizedSingleTap(gesture: UITapGestureRecognizer) {
let location = gesture.locationInView(tableView)
if let indexPath = tableView.indexPathForRowAtPoint(location), cell = tableView.cellForRowAtIndexPath(indexPath) {
Util.animateButtonPress(button: cell)
displayNoteDetail(indexPath: indexPath, create: false)
}
}
func gestureRecognizedDoubleTap(gesture: UITapGestureRecognizer) {
let location = gesture.locationInView(tableView)
if let indexPath = tableView.indexPathForRowAtPoint(location) {
let item = notebook.display[indexPath.row]
if item.collapsed {
notebook.uncollapse(indexPath: indexPath, tableView: tableView)
} else {
notebook.collapse(indexPath: indexPath, tableView: tableView)
}
Util.playSound(systemSound: .Tap)
}
}
// MARK: - shake
override func canBecomeFirstResponder() -> Bool {
return true
}
override func motionEnded(motion: UIEventSubtype, withEvent event: UIEvent?) {
if let event = event where event.subtype == .MotionShake {
displayDeleteCompleted()
}
}
// MARK: - buttons
func settingsButtonPressed(button button: SettingViewController.Button) {
switch button.detail {
case .NotebookTitle: displayNotebookTitle()
case .NotebookCollapse: notebook.collapseAll(tableView: tableView)
case .NotebookUncollapse: notebook.uncollapseAll(tableView: tableView)
case .NotebookHideReminder: displayToggleReminders(button: button)
case .NotebookDeleteCompleted: displayDeleteCompleted()
case .AppTutorial: displayAppTutorial()
case .AppTimer: displayAppTimer(button: button)
case .AppColor: displayAppColor()
case .AppFeedback: displayAppFeedback()
case .AppShare: displayAppShare()
case .AccountEmail: displayAccountEmail()
case .AccountPassword: displayAccountPassword()
case .AccountDelete: displayAccountDelete()
case .AccountLogout: attemptLogout()
default: break
}
}
private func displayToggleReminders(button button: SettingViewController.Button) {
updateSettingsMenuButtonTitle(button: button, userDefaultRawKey: Constant.UserDefault.Key.IsRemindersHidden.rawValue)
}
func cellAccessoryButtonPressed(cell cell: UITableViewCell) {
if let indexPath = tableView.indexPathForCell(cell) {
let item = notebook.display[indexPath.row]
if item.collapsed {
notebook.uncollapse(indexPath: indexPath, tableView: tableView)
} else {
displayNoteDetail(indexPath: NSIndexPath(forRow: indexPath.row+1, inSection: indexPath.section), create: true)
}
}
}
func addButtonPressed(button: UIButton) {
Util.animateButtonPress(button: button)
displayNoteDetail(indexPath: NSIndexPath(forRow: 0, inSection: 0), create: true)
}
private func displayLogout() {
let modal = ModalError()
modal.message = "An error has occured and you will need to log back in"
modal.show(controller: self) { output in
self.logout()
}
}
private func attemptLogout() {
Remote.Auth.logout(controller: self, notebook: notebook) { error in
if let error = error {
let modal = ModalError()
modal.message = error
modal.show(controller: self)
return
}
self.logout()
}
}
private func logout() {
Util.threadBackground {
LocalNotification.sharedInstance.destroy()
}
Report.sharedInstance.track(event: "logout")
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: - modals
private func displayNotebookTitle() {
let modal = ModalTextField()
modal.limit = 20
modal.placeholder = notebook.title
modal.show(controller: self, dismissible: true) { output in
if let title = output[ModalTextField.OutputKeys.Text.rawValue] as? String {
self.notebook.title = title
self.updateTitle()
}
}
}
private func displayReview() {
Report.sharedInstance.track(event: "show_review")
let modal = ModalReview()
modal.show(controller: self) { output in
if let selection = output[ModalReview.OutputKeys.Selection.rawValue] as? Int {
Constant.UserDefault.set(key: Constant.UserDefault.Key.ReviewCount, val: 0)
let modal = ModalConfirmation()
if selection >= 3 {
modal.message = "Can you help us by leaving a review?"
modal.show(controller: self) { output in
Constant.UserDefault.set(key: Constant.UserDefault.Key.ReviewApp, val: true)
Report.sharedInstance.track(event: "sent_review")
UIApplication.sharedApplication().openURL(NSURL(string: "itms-apps://itunes.apple.com/app/?id=" + Constant.App.id)!)
}
} else {
modal.message = "Can you tell us how we can improve?"
modal.show(controller: self) { output in
self.displayAppFeedback()
}
}
}
}
}
private func displayAppTutorial() {
let modal = ModalTutorial()
modal.show(controller: self, dismissible: true)
}
private func updateSettingsMenuButtonTitle(button button: SettingViewController.Button, userDefaultRawKey: String) {
if let key = Constant.UserDefault.Key(rawValue: userDefaultRawKey) {
let hide: Bool = Constant.UserDefault.get(key: key) as? Bool ?? false
Constant.UserDefault.set(key: key, val: !hide)
button.button.setTitle(button.detail.title, forState: .Normal)
}
}
private func displayAppTimer(button button: SettingViewController.Button) {
guard let navigationController = navigationController as? MenuNavigationController else {
return Report.sharedInstance.log("unable to get the correct parent navigation controller of MenuNavigationController")
}
// handle alert text
let timer = navigationController.timer
let modal = ModalConfirmation()
modal.message = timer.state == .On || timer.state == .Paused ? "Pomodoro Timer" : "Create a Pomodoro Timer to track your productivity?"
modal.left = timer.state == .On ? "Stop" : timer.state == .Paused ? "Stop" : "Cancel"
modal.right = timer.state == .On ? "Pause" : timer.state == .Paused ? "Resume" : "Start"
modal.trackButtons = true
modal.show(controller: self, dismissible: true) { output in
if let selection = output[ModalConfirmation.OutputKeys.Selection.rawValue] as? Int {
// operate timer
if selection == 1 {
switch timer.state {
case .On:
timer.pause()
case .Off:
timer.start()
case .Paused:
timer.start()
}
} else {
switch timer.state {
case .On, .Paused:
timer.stop()
case .Off: break
}
}
// change settings side menu title
let on = navigationController.timer.state != .Off
let active = Constant.UserDefault.get(key: Constant.UserDefault.Key.IsTimerActive) as? Bool ?? false
if on != active {
Constant.UserDefault.set(key: Constant.UserDefault.Key.IsTimerActive, val: navigationController.timer.state != .Off)
button.button.setTitle(button.detail.title, forState: .Normal)
}
}
}
}
private func displayAppColor() {
Constant.Color.toggleColor()
dismissViewControllerAnimated(true, completion: nil)
}
private func displayDeleteCompleted() {
if notebook.hasCompleted {
let modal = ModalConfirmation()
modal.message = "Permanently delete all completed?"
modal.show(controller: self, dismissible: false) { (output) in
self.notebook.deleteCompleted(tableView: self.tableView)
}
}
}
private func displayDeleteCell(indexPath indexPath: NSIndexPath) {
let modal = ModalConfirmation()
modal.message = "Permanently delete?"
modal.show(controller: self, dismissible: false) { (output) in
self.notebook.delete(indexPath: indexPath, tableView: self.tableView)
}
}
private func displayReminder(indexPath indexPath: NSIndexPath) {
let note = notebook.display[indexPath.row]
if !note.completed {
let modal = ModalReminder()
modal.reminder = note.reminder ?? nil
modal.show(controller: self, dismissible: true, completion: { (output) in
if let id = output[ModalReminder.OutputKeys.ReminderType.rawValue] as? Int, let reminderType = ReminderType(rawValue: id) {
if reminderType == .None {
return
}
if reminderType == .Date {
if let reminder = self.notebook.display[indexPath.row].reminder where reminder.type == .Date && reminder.date.timeIntervalSinceNow > 0 {
// delete custom date
self.createReminder(indexPath: indexPath, type: reminderType, date: nil)
} else {
// create custom date
self.displayReminderDatePicker(indexPath: indexPath)
}
} else {
// delete and create select date
self.createReminder(indexPath: indexPath, type: reminderType, date: nil)
}
}
})
}
}
private func displayReminderDatePicker(indexPath indexPath: NSIndexPath) {
let modal = ModalDatePicker()
modal.show(controller: self, dismissible: true) { (output) in
if let date = output[ModalDatePicker.OutputKeys.Date.rawValue] as? NSDate {
self.createReminder(indexPath: indexPath, type: .Date, date: date)
}
}
}
private func createReminder(indexPath indexPath: NSIndexPath, type: ReminderType, date: NSDate?) {
notebook.reminder(indexPath: indexPath, controller: self, tableView: tableView, reminderType: type, date: date) { success, create in
if success {}
}
}
private func displayAppFeedback() {
if MFMailComposeViewController.canSendMail() {
let mail = MFMailComposeViewController()
mail.mailComposeDelegate = self
mail.setToRecipients(["[email protected]"])
mail.setSubject("I have feedback for your Organize app!")
mail.setMessageBody("<p>Hey Ethan,</p></br>", isHTML: true)
presentViewController(mail, animated: true, completion: nil)
} else {
let modal = ModalError()
modal.message = "Please check your email configuration and try again"
modal.show(controller: self)
}
}
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
Util.playSound(systemSound: .Tap)
if result.rawValue == 2 {
Constant.UserDefault.set(key: Constant.UserDefault.Key.FeedbackApp, val: true)
Report.sharedInstance.track(event: "sent_feedback")
}
}
private func displayAppShare() {
let shareContent: String = "Check out this app!\n\nI've been using it quite a bit and I think you'll like it too. Tell me what you think.\n\n" + Constant.App.deepLinkUrl
let activityViewController: ActivityViewController = ActivityViewController(activityItems: [shareContent], applicationActivities: nil)
activityViewController.excludedActivityTypes = [UIActivityTypeAirDrop]
presentViewController(activityViewController, animated: true, completion: nil)
}
private func displayAccountEmail() {
let modal = ModalTextField()
modal.placeholder = Remote.Auth.user?.email ?? "new email"
modal.keyboardType = .EmailAddress
modal.show(controller: self, dismissible: true) { (output) in
if let email = output[ModalTextField.OutputKeys.Text.rawValue] as? String where email.isEmail {
Remote.Auth.changeEmail(controller: self, email: email, completion: { error in
// FIXME: catch error 17014 and force logout? (minor)
// FIXME: if no wifi on simulator, causes a flash in modals because loading.hide happens before loading.show finshes (minor)
let message = error ?? "Log back in with your new email"
let modal = ModalError()
modal.message = message
modal.show(controller: self) { (output) in
if let _ = error {
// close
} else {
self.attemptLogout()
}
}
})
} else {
let modal = ModalError()
modal.message = AccessBusinessLogic.ErrorMessage.EmailInvalid.message
modal.show(controller: self) { (output) in
// FIXME: pass previous text through
self.displayAccountEmail()
}
}
}
}
private func displayAccountPassword() {
let modal = ModalTextField()
modal.placeholder = "new password"
modal.secureEntry = true
modal.show(controller: self, dismissible: true) { (output) in
if let password = output[ModalTextField.OutputKeys.Text.rawValue] as? String where password.isPassword {
Remote.Auth.changePassword(controller: self, password: password, completion: { error in
let message = error ?? "Log back in with your new email"
let modal = ModalError()
modal.message = message
modal.show(controller: self) { (output) in
if let _ = error {
// close
} else {
self.attemptLogout()
}
}
})
} else {
let modal = ModalError()
modal.message = AccessBusinessLogic.ErrorMessage.PasswordInvalid.message
modal.show(controller: self, dismissible: true) { (output) in
self.displayAccountEmail()
}
}
}
}
private func displayAccountDelete() {
let modal = ModalConfirmation()
modal.message = "Permanently delete account and all data related to it?"
modal.show(controller: self, dismissible: true) { (output) in
Remote.Auth.delete(controller: self, completion: { (error) in
if let error = error {
let modal = ModalError()
modal.message = error
modal.show(controller: self)
} else {
self.logout()
}
})
}
}
private func displayUndo() {
let modal = ModalConfirmation()
modal.message = "Undo last action?"
modal.show(controller: self, dismissible: false) { (output) in
self.notebook.undo(tableView: self.tableView)
}
}
private func displayNoteDetail(indexPath indexPath: NSIndexPath, create: Bool) {
let note: Note? = create ? nil : notebook.display[indexPath.row]
let modal = ModalNoteDetail()
modal.note = note
modal.show(controller: self, dismissible: false) { (output) in
if let note = output[ModalNoteDetail.OutputKeys.Note.rawValue] as? Note {
if create {
self.notebook.create(indexPath: indexPath, tableView: self.tableView, note: note)
} else {
self.notebook.update(indexPath: indexPath, tableView: self.tableView, note: note)
}
}
}
}
} | mit | 47493486a696cd65045dbf04780a5c26 | 38.076316 | 218 | 0.691551 | 4.761424 | false | false | false | false |
wibosco/WhiteBoardCodingChallenges | WhiteBoardCodingChallenges/Challenges/HackerRank/TimeConverter/TimeConverter.swift | 1 | 648 | //
// TimeConverter.swift
// WhiteBoardCodingChallenges
//
// Created by Boles on 07/05/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
//https://www.hackerrank.com/challenges/time-conversion
class TimeConverter: NSObject {
class func convertFrom12HourTo24HourUsingDateManipulation(time: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "h:mm:ssa"
let date12 = dateFormatter.date(from: time)
dateFormatter.dateFormat = "HH:mm:ss"
let date24 = dateFormatter.string(from: date12!)
return date24
}
}
| mit | 7994afc4635ed5cb4c56d15728e681a5 | 24.88 | 87 | 0.659969 | 4.201299 | false | false | false | false |
lieven/fietsknelpunten-ios | FietsknelpuntenAPI/API+Tags.swift | 1 | 1590 | //
// API+Tags.swift
// Fietsknelpunten
//
// Created by Lieven Dekeyser on 12/11/16.
// Copyright © 2016 Fietsknelpunten. All rights reserved.
//
import Foundation
extension API
{
public func getTags(completion: @escaping (Bool, [TagGroup]?, Error?)->())
{
self.sendRequest(action: "tags", arguments: nil)
{
(success, response, error) in
if success
{
if let groupDicts = response as? [[AnyHashable: Any]]
{
var groups = [TagGroup]()
for groupDict in groupDicts
{
if let group = TagGroup(dictionary: groupDict)
{
groups.append(group)
}
}
completion(true, groups, nil)
}
else
{
completion(false, nil, nil)
}
}
else
{
completion(false, nil, error)
}
}
}
}
extension Tag
{
convenience init?(dictionary: [AnyHashable: Any])
{
guard let identifier = dictionary.string(forKey: "id", allowConversion: true), let name = dictionary["name"] as? String else
{
return nil
}
self.init(identifier: identifier, name: name, info: dictionary["info"] as? String)
}
}
extension TagGroup
{
convenience init?(dictionary: [AnyHashable: Any])
{
guard let identifier = dictionary.string(forKey: "id", allowConversion: true), let name = dictionary["name"] as? String, let tagDicts = dictionary["tags"] as? [[AnyHashable: Any]] else
{
return nil
}
var tags = [Tag]()
for tagDict in tagDicts
{
if let tag = Tag(dictionary: tagDict)
{
tags.append(tag)
}
}
self.init(identifier: identifier, name: name, tags: tags)
}
}
| mit | 79a71574bf716e73314b60b0991b05e7 | 18.144578 | 186 | 0.623663 | 3.262834 | false | false | false | false |
Johennes/firefox-ios | Client/Frontend/Widgets/HighlightCell.swift | 1 | 7784 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
struct HighlightCellUX {
static let BorderColor = UIColor.blackColor().colorWithAlphaComponent(0.1)
static let BorderWidth = CGFloat(0.5)
static let LabelColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : UIColor(rgb: 0x353535)
static let LabelBackgroundColor = UIColor(white: 1.0, alpha: 0.5)
static let LabelAlignment: NSTextAlignment = .Left
static let SelectedOverlayColor = UIColor(white: 0.0, alpha: 0.25)
static let PlaceholderImage = UIImage(named: "defaultTopSiteIcon")
static let CornerRadius: CGFloat = 3
static let NearestNeighbordScalingThreshold: CGFloat = 24
}
class HighlightCell: UITableViewCell {
var siteImage: UIImage? = nil {
didSet {
if let image = siteImage {
siteImageView.image = image
siteImageView.contentMode = UIViewContentMode.ScaleAspectFit
// Force nearest neighbor scaling for small favicons
if image.size.width < HighlightCellUX.NearestNeighbordScalingThreshold {
siteImageView.layer.shouldRasterize = true
siteImageView.layer.rasterizationScale = 2
siteImageView.layer.minificationFilter = kCAFilterNearest
siteImageView.layer.magnificationFilter = kCAFilterNearest
}
} else {
siteImageView.image = HighlightCellUX.PlaceholderImage
siteImageView.contentMode = UIViewContentMode.Center
}
}
}
lazy var titleLabel: UILabel = {
let textLabel = UILabel()
textLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
textLabel.font = DynamicFontHelper.defaultHelper.DeviceFontMediumBold
textLabel.textColor = HighlightCellUX.LabelColor
textLabel.textAlignment = HighlightCellUX.LabelAlignment
textLabel.numberOfLines = 2
return textLabel
}()
lazy var timeStamp: UILabel = {
let textLabel = UILabel()
textLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
textLabel.font = DynamicFontHelper.defaultHelper.DeviceFontSmallActivityStream
textLabel.textColor = UIColor(colorString: "D4D4D4")
textLabel.textAlignment = HighlightCellUX.LabelAlignment
return textLabel
}()
lazy var siteImageView: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = UIViewContentMode.ScaleAspectFit
siteImageView.clipsToBounds = true
siteImageView.layer.cornerRadius = HighlightCellUX.CornerRadius
return siteImageView
}()
lazy var statusIcon: UIImageView = {
let siteImageView = UIImageView()
siteImageView.contentMode = UIViewContentMode.ScaleAspectFit
siteImageView.clipsToBounds = true
siteImageView.layer.cornerRadius = HighlightCellUX.CornerRadius
return siteImageView
}()
lazy var descriptionLabel: UILabel = {
let textLabel = UILabel()
textLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Vertical)
textLabel.font = DynamicFontHelper.defaultHelper.DeviceFontDescriptionActivityStream
textLabel.textColor = UIColor(colorString: "919191")
textLabel.textAlignment = .Left
textLabel.numberOfLines = 1
return textLabel
}()
lazy var backgroundImage: UIImageView = {
let backgroundImage = UIImageView()
backgroundImage.contentMode = UIViewContentMode.ScaleAspectFill
backgroundImage.layer.borderColor = HighlightCellUX.BorderColor.CGColor
backgroundImage.layer.borderWidth = HighlightCellUX.BorderWidth
backgroundImage.layer.cornerRadius = HighlightCellUX.CornerRadius
backgroundImage.clipsToBounds = true
return backgroundImage
}()
lazy var selectedOverlay: UIView = {
let selectedOverlay = UIView()
selectedOverlay.backgroundColor = HighlightCellUX.SelectedOverlayColor
selectedOverlay.hidden = true
return selectedOverlay
}()
override var selected: Bool {
didSet {
self.selectedOverlay.hidden = !selected
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.mainScreen().scale
isAccessibilityElement = true
contentView.addSubview(selectedOverlay)
contentView.addSubview(backgroundImage)
contentView.addSubview(siteImageView)
contentView.addSubview(titleLabel)
contentView.addSubview(timeStamp)
contentView.addSubview(descriptionLabel)
contentView.addSubview(statusIcon)
siteImageView.snp_makeConstraints { make in
make.top.equalTo(backgroundImage)
make.leading.equalTo(backgroundImage)
make.size.equalTo(48)
}
backgroundImage.snp_makeConstraints { make in
make.top.equalTo(contentView).offset(5)
make.leading.equalTo(contentView).offset(20)
make.trailing.equalTo(contentView).inset(20)
make.height.equalTo(200)
}
selectedOverlay.snp_makeConstraints { make in
make.edges.equalTo(contentView)
}
titleLabel.snp_remakeConstraints { make in
make.leading.equalTo(contentView).offset(20)
make.top.equalTo(backgroundImage.snp_bottom).offset(10)
make.trailing.equalTo(timeStamp.snp_leading).offset(-5)
}
statusIcon.snp_makeConstraints { make in
make.leading.equalTo(backgroundImage)
make.top.equalTo(titleLabel.snp_bottom).offset(8)
make.bottom.equalTo(contentView).offset(-12)
make.size.equalTo(12)
}
descriptionLabel.snp_makeConstraints { make in
make.leading.equalTo(statusIcon.snp_trailing).offset(10)
make.bottom.equalTo(statusIcon)
}
timeStamp.snp_makeConstraints { make in
make.trailing.equalTo(backgroundImage)
make.bottom.equalTo(descriptionLabel)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareForReuse() {
super.prepareForReuse()
siteImageView.layer.borderWidth = 0
}
func setImageWithURL(url: NSURL) {
siteImageView.sd_setImageWithURL(url) { (img, err, type, url) -> Void in
guard let img = img else {
return
}
self.siteImage = img
}
backgroundImage.sd_setImageWithURL(NSURL(string: "http://lorempixel.com/640/480/?r=" + String(arc4random())))
siteImageView.layer.masksToBounds = true
}
func configureHighlightCell(site: Site) {
if let icon = site.icon {
let url = icon.url
self.setImageWithURL(NSURL(string: url)!)
} else {
self.siteImage = FaviconFetcher.getDefaultFavicon(NSURL(string: site.url)!)
self.siteImageView.layer.borderWidth = 0.5
}
self.titleLabel.text = site.title.characters.count <= 1 ? site.url : site.title
self.descriptionLabel.text = "Bookmarked"
self.statusIcon.image = UIImage(named: "bookmarked_passive")
self.timeStamp.text = "3 days ago"
}
}
| mpl-2.0 | a1d0e9c0afcc47aa5b71f43284b7283f | 38.115578 | 118 | 0.66945 | 5.231183 | false | false | false | false |
knutigro/AppReviews | ReviewManager/PersistentStack.swift | 1 | 6949 | //
// PersistentStack.swift
// App Reviews
//
// Created by Knut Inge Grosland on 2015-04-09.
// Copyright (c) 2015 Cocmoc. All rights reserved.
//
import Foundation
import AppKit
let kDidAddReviewsNotification = "kDidAddReviewsNotification"
let kDidUpdateApplicationNotification = "kDidUpdateApplicationNotification"
let kDidUpdateApplicationSettingsNotification = "kDidUpdateApplicationSettingsNotification"
let kDidUpdateReviewsNotification = "kDidUpdateReviewsNotification"
class PersistentStack {
var managedObjectContext: NSManagedObjectContext!
var modelURL: NSURL
var storeURL: NSURL
init(storeURL: NSURL, modelURL: NSURL) {
self.modelURL = modelURL
self.storeURL = storeURL
setupManagedObjectContexts()
}
func setupManagedObjectContexts() {
managedObjectContext = setupManagedObjectContextWithConcurrencyType(.MainQueueConcurrencyType)
managedObjectContext.undoManager = NSUndoManager()
_ = NSNotificationCenter.defaultCenter().addObserverForName(NSManagedObjectContextDidSaveNotification, object: nil, queue: nil) { [weak self] notification in
self?.managedObjectDidSave(notification)
}
}
func managedObjectDidSave(notification: NSNotification) {
let moc = managedObjectContext;
if notification.object as? NSManagedObjectContext != moc {
moc.performBlock({ [weak self] () -> Void in
self?.mergeChangesFromSaveNotification(notification, intoContext: moc)
var newReviews = Set<NSManagedObjectID>()
var updatedReviews = Set<NSManagedObjectID>()
var updatedApplications = Set<NSManagedObjectID>()
var updatedApplicationSettings = Set<NSManagedObjectID>()
if let insertedObjects = notification.userInfo?[NSInsertedObjectsKey] as? NSSet {
for object in insertedObjects {
if let application = object as? Application {
updatedApplications.insert(application.objectID)
}
if let review = object as? Review {
newReviews.insert(review.objectID)
updatedReviews.insert(review.objectID)
}
if let application = object as? ApplicationSettings {
updatedApplicationSettings.insert(application.objectID)
}
}
}
if let deletedObjects = notification.userInfo?[NSDeletedObjectsKey] as? NSSet {
for object in deletedObjects {
if let application = object as? Application {
updatedApplications.insert(application.objectID)
}
if let review = object as? Review {
updatedReviews.insert(review.objectID)
}
if let settings = object as? ApplicationSettings {
updatedApplicationSettings.insert(settings.objectID)
}
}
}
if let updatedObjects = notification.userInfo?[NSUpdatedObjectsKey] as? NSSet {
for object in updatedObjects {
if let application = object as? Application {
updatedApplications.insert(application.objectID)
}
if let review = object as? Review {
updatedReviews.insert(review.objectID)
}
if let settings = object as? ApplicationSettings {
updatedApplicationSettings.insert(settings.objectID)
}
}
}
if !newReviews.isEmpty {
NSNotificationCenter.defaultCenter().postNotificationName(kDidAddReviewsNotification, object: newReviews)
}
if !updatedApplications.isEmpty {
NSNotificationCenter.defaultCenter().postNotificationName(kDidUpdateApplicationNotification, object: updatedApplications)
}
if !updatedReviews.isEmpty {
NSNotificationCenter.defaultCenter().postNotificationName(kDidUpdateReviewsNotification, object: newReviews)
}
if !updatedApplicationSettings.isEmpty {
NSNotificationCenter.defaultCenter().postNotificationName(kDidUpdateApplicationSettingsNotification, object: updatedApplicationSettings)
}
})
}
}
func mergeChangesFromSaveNotification(notification: NSNotification, intoContext context: NSManagedObjectContext) {
// // NSManagedObjectContext's merge routine ignores updated objects which aren't
// // currently faulted in. To force it to notify interested clients that such
// // objects have been refreshed (e.g. NSFetchedResultsController) we need to
// // force them to be faulted in ahead of the merge
if let updatedObjects = notification.userInfo?[NSInsertedObjectsKey] as? NSSet {
for anyObject in updatedObjects {
if let managedObject = anyObject as? NSManagedObject {
do {
try context.existingObjectWithID(managedObject.objectID)
} catch let error as NSError {
print(error)
} catch {
fatalError()
}
}
}
}
context.mergeChangesFromContextDidSaveNotification(notification)
}
func setupManagedObjectContextWithConcurrencyType(concurrencyType: NSManagedObjectContextConcurrencyType) -> NSManagedObjectContext {
let managedObjectContext = NSManagedObjectContext(concurrencyType: concurrencyType)
if let managedObjectModel = managedObjectModel() {
managedObjectContext.persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try managedObjectContext.persistentStoreCoordinator?.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil)
} catch let error as NSError {
print(storeURL.path)
print(error)
}
}
return managedObjectContext;
}
func managedObjectModel() -> NSManagedObjectModel? {
return NSManagedObjectModel(contentsOfURL: modelURL)
}
} | gpl-3.0 | 6b6b8553c3675b657dba6ba9ed58dc12 | 45.02649 | 165 | 0.587998 | 6.772904 | false | false | false | false |
andrea-prearo/SwiftExamples | CoreDataCodable/CoreDataCodable/ViewModels/UserViewModel.swift | 1 | 761 | //
// UserViewModel.swift
// CoreDataCodable
//
// Created by Andrea Prearo on 3/29/18.
// Copyright © 2018 Andrea Prearo. All rights reserved.
//
import Foundation
struct UserViewModel {
let avatarUrl: String
let username: String
let role: String
init(user: UserManagedObject) {
// Avatar
avatarUrl = String.emptyIfNil(user.avatarUrl)
// Username
username = String.emptyIfNil(user.username)
// Role
role = String.emptyIfNil(user.role.rawValue)
}
}
extension UserViewModel: Equatable {}
func ==(lhs: UserViewModel, rhs: UserViewModel) -> Bool {
return lhs.avatarUrl == rhs.avatarUrl &&
lhs.username == rhs.username &&
lhs.role == rhs.role
}
| mit | 95bc03a9863e76acd600d2e11ceab2de | 21.352941 | 57 | 0.626316 | 4.24581 | false | false | false | false |
jspenc72/AVFoundationRecorder | AVFoundation Recorder/RecordingCollectionViewCell.swift | 2 | 711 | //
// RecordingCollectionViewCell.swift
// AVFoundation Recorder
//
// Created by Gene De Lisa on 8/13/14.
// Copyright (c) 2014 Gene De Lisa. All rights reserved.
//
import UIKit
class RecordingCollectionViewCell: UICollectionViewCell {
@IBOutlet var label: UILabel!
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
var view = UIView(frame:self.frame)
view.autoresizingMask = .FlexibleWidth | .FlexibleHeight
view.backgroundColor = UIColor(red: 0.2, green: 0.6, blue: 1.0, alpha: 1.0)
view.layer.borderColor = UIColor.whiteColor().CGColor
view.layer.borderWidth = 4
self.selectedBackgroundView = view
}
}
| mit | 2f145d738bdba6f3c9e694a20dca2064 | 27.44 | 83 | 0.673699 | 4.133721 | false | false | false | false |
kostiakoval/WatchKit-Apps | Carthage/Checkouts/Seru/Seru/Source/Fetch/FetchResultController.swift | 8 | 1379 | //
// FetchResultController.swift
// Seru
//
// Created by Konstantin Koval on 29/08/14.
// Copyright (c) 2014 Konstantin Koval. All rights reserved.
//
import Foundation
import CoreData
public class FetchResultController {
public class func make(moc: NSManagedObjectContext, entityName: String, sortKey: String, ascending: Bool = false, fetchBatchSize: Int = 20) -> NSFetchedResultsController {
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName(entityName, inManagedObjectContext: moc)
fetchRequest.entity = entity
fetchRequest.fetchBatchSize = fetchBatchSize
fetchRequest.sortDescriptors = [NSSortDescriptor(key: sortKey, ascending: ascending)]
return make(moc, fetchRequest: fetchRequest)
}
public class func make(moc: NSManagedObjectContext, fetchRequest: NSFetchRequest, sectionNameKeyPath: String! = nil, cacheName: String! = nil) -> NSFetchedResultsController {
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: moc, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName)
return aFetchedResultsController
}
public class func fetch(fetchRC: NSFetchedResultsController, errorHandler: ErrorHandler) {
var error: NSError? = nil
if !fetchRC.performFetch(&error) {
errorHandler.handle(error!)
}
}
} | mit | e196475298f75c08ce5bbc5015853e90 | 37.333333 | 181 | 0.764322 | 5.283525 | false | false | false | false |
Sherlouk/IGListKit | Examples/Examples-iOS/IGListKitExamples/SectionControllers/FeedItemSectionController.swift | 4 | 2605 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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.
*/
import IGListKit
final class FeedItemSectionController: IGListSectionController, IGListSectionType, IGListSupplementaryViewSource {
var feedItem: FeedItem!
override init() {
super.init()
supplementaryViewSource = self
}
// MARK: IGlistSectionType
func numberOfItems() -> Int {
return feedItem.comments.count
}
func sizeForItem(at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 55)
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext?.dequeueReusableCell(of: LabelCell.self, for: self, at: index) as! LabelCell
cell.label.text = feedItem.comments[index]
return cell
}
func didUpdate(to object: Any) {
feedItem = object as? FeedItem
}
func didSelectItem(at index: Int) {}
// MARK: IGListSupplementaryViewSource
func supportedElementKinds() -> [String] {
return [UICollectionElementKindSectionHeader]
}
func viewForSupplementaryElement(ofKind elementKind: String, at index: Int) -> UICollectionReusableView {
let view = collectionContext?.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader,
for: self,
nibName: "UserHeaderView",
bundle: nil,
at: index) as! UserHeaderView
view.handleLabel.text = "@" + feedItem.user.handle
view.nameLabel.text = feedItem.user.name
return view
}
func sizeForSupplementaryView(ofKind elementKind: String, at index: Int) -> CGSize {
return CGSize(width: collectionContext!.containerSize.width, height: 40)
}
}
| bsd-3-clause | ca7da6fea90b0523a083df96b263ff81 | 36.753623 | 116 | 0.643378 | 5.566239 | false | false | false | false |
zapdroid/RXWeather | Pods/RxSwift/RxSwift/Disposables/ScheduledDisposable.swift | 1 | 1527 | //
// ScheduledDisposable.swift
// RxSwift
//
// Created by Krunoslav Zaher on 6/13/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
private let disposeScheduledDisposable: (ScheduledDisposable) -> Disposable = { sd in
sd.disposeInner()
return Disposables.create()
}
/// Represents a disposable resource whose disposal invocation will be scheduled on the specified scheduler.
public final class ScheduledDisposable: Cancelable {
public let scheduler: ImmediateSchedulerType
private var _isDisposed: AtomicInt = 0
// state
private var _disposable: Disposable?
/// - returns: Was resource disposed.
public var isDisposed: Bool {
return _isDisposed == 1
}
/**
Initializes a new instance of the `ScheduledDisposable` that uses a `scheduler` on which to dispose the `disposable`.
- parameter scheduler: Scheduler where the disposable resource will be disposed on.
- parameter disposable: Disposable resource to dispose on the given scheduler.
*/
public init(scheduler: ImmediateSchedulerType, disposable: Disposable) {
self.scheduler = scheduler
_disposable = disposable
}
/// Disposes the wrapped disposable on the provided scheduler.
public func dispose() {
_ = scheduler.schedule(self, action: disposeScheduledDisposable)
}
func disposeInner() {
if AtomicCompareAndSwap(0, 1, &_isDisposed) {
_disposable!.dispose()
_disposable = nil
}
}
}
| mit | f05456dea550e7dc983dfa6d19a4cf34 | 29.52 | 122 | 0.686763 | 4.970684 | false | false | false | false |
huonw/swift | validation-test/Evolution/Inputs/bitwise_takable.swift | 5 | 1444 | public protocol Reporter {
func report() -> String;
}
public class Subject {
public var value = 1
public init(_ v: Int) {
value = v
}
}
public var s2 = Subject(2)
public var s3 = Subject(3)
public var s4 = Subject(4)
public var s5 = Subject(5)
public struct Container : Reporter {
#if BEFORE
public var v : Subject
#else
weak public var v : Subject?
#endif
public init(_ s: Subject) {
v = s
}
public func report() -> String{
#if BEFORE
return "Container(\(v.value))"
#else
return "Container(\(v!.value))"
#endif
}
}
public func createContainerReporter() -> Reporter {
return Container(s2)
}
public struct PairContainer: Reporter {
public var pair : (Container, Container)
public init(_ p : (Container, Container)) {
pair = p
}
public func report() -> String {
return "PairContainer(\(pair.0.report()), \(pair.1.report()))"
}
}
public func createPairContainerReporter() -> Reporter {
return PairContainer((Container(s3), Container(s4)))
}
public enum EnumContainer : Reporter {
case Empty
case Some(Container)
public func report() -> String {
switch self {
case .Empty:
return "EnumContainer Empty"
case .Some(let c):
return "EnumContainer(\(c.report()))"
}
}
}
public func createEnumContainerReporter() -> Reporter {
return EnumContainer.Some(Container(s5))
}
public func report(_ r: Reporter) -> String {
return r.report()
}
| apache-2.0 | d6b276e2d79b6049cd8cba6175cfcb10 | 18.780822 | 66 | 0.65097 | 3.619048 | false | false | false | false |
fdanise/loadingButton | ExtensionUIButton.swift | 1 | 3312 | //
// ExtensionUIButton.swift
//
// Created by Ferdinando Danise on 07/09/17.
// Copyright © 2017 Ferdinando Danise. All rights reserved.
//
import UIKit
extension UIButton {
func startLoading(color: UIColor) {
let shapeOuter = shapeLayerOuter(color: color)
let shapeInner = shapeLayerInner(color: color)
shapeOuter.add(animationOuter(), forKey: nil)
shapeInner.add(animationInner(), forKey: nil)
self.layer.addSublayer(shapeOuter)
self.layer.addSublayer(shapeInner)
}
func stopLoading(){
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseOut, animations: {
self.alpha = 0
}) { (true) in
self.layer.removeFromSuperlayer()
}
}
private func shapeLayerOuter(color: UIColor) -> CAShapeLayer{
let circleOut = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY),
radius: CGFloat(self.bounds.height * 0.4),
startAngle: CGFloat(0),
endAngle:CGFloat(Double.pi * 2),
clockwise: true)
let shapeLayerOut = CAShapeLayer()
shapeLayerOut.path = circleOut.cgPath
shapeLayerOut.fillColor = UIColor.clear.cgColor
shapeLayerOut.strokeColor = color.cgColor
shapeLayerOut.strokeStart = 0.1
shapeLayerOut.strokeEnd = 1
shapeLayerOut.lineWidth = 3.5
shapeLayerOut.lineCap = "round"
shapeLayerOut.frame = self.bounds
return shapeLayerOut
}
private func shapeLayerInner(color: UIColor) -> CAShapeLayer{
let circleIn = UIBezierPath(arcCenter: CGPoint(x: self.bounds.midX, y: self.bounds.midY),
radius: CGFloat(self.bounds.height * 0.2),
startAngle: CGFloat(0),
endAngle: CGFloat(Double.pi * 2),
clockwise: false)
let shapeLayerIn = CAShapeLayer()
shapeLayerIn.path = circleIn.cgPath
shapeLayerIn.fillColor = UIColor.clear.cgColor
shapeLayerIn.strokeColor = color.cgColor
shapeLayerIn.strokeStart = 0.1
shapeLayerIn.strokeEnd = 1
shapeLayerIn.lineWidth = 3.2
shapeLayerIn.lineCap = "round"
shapeLayerIn.frame = self.bounds
return shapeLayerIn
}
private func animationOuter() -> CABasicAnimation{
let animationOut = CABasicAnimation(keyPath: "transform.rotation")
animationOut.fromValue = 0
animationOut.toValue = Double.pi * 2
animationOut.duration = 1
animationOut.repeatCount = Float.infinity
return animationOut
}
private func animationInner() -> CABasicAnimation {
let animationIn = CABasicAnimation(keyPath: "transform.rotation")
animationIn.fromValue = 0
animationIn.toValue = -(Double.pi * 2)
animationIn.duration = 1
animationIn.repeatCount = Float.infinity
return animationIn
}
}
| mit | c16dd1a2138d63731d53995964620237 | 31.782178 | 98 | 0.57022 | 5.133333 | false | false | false | false |
MaximAlien/SwiftyNetworking | SwiftyNetworkingTests/URLCacheManagerTests.swift | 1 | 2428 | //
// URLCacheManagerTests.swift
// SwiftyNetworking
//
// Created by Maxim Makhun on 11/19/16.
// Copyright © 2016 Maxim Makhun. All rights reserved.
//
import XCTest
class URLCacheManagerTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testThat_dataRequest_shouldHandleCacheReuse() {
print("Started cache request")
// make session task synchronous
let expectation: XCTestExpectation = self.expectation(description: "Simple request expectation")
// make request
let session = URLSession.shared
var sessionTask: URLSessionTask = URLSessionTask()
sessionTask = session.dataTask(with: Constants.requestURL) { (data, response, error) in
XCTAssertNil(error, "Error should be nil")
if let data = data {
URLCacheManager.sharedInstance.cacheData(for: sessionTask, data: data)
print("Original data: \(data)")
} else {
XCTAssertNotNil(data, "Data should not be nil")
}
// attempt to load data from cache
if let cachedData = URLCacheManager.sharedInstance.cache(for: sessionTask) {
print("Cached data: \(cachedData)")
} else {
print("Cached response data not found")
XCTAssertFalse(true, "Cached response should be found")
}
if let response = response {
let httpResponse = response as! HTTPURLResponse
XCTAssertEqual(httpResponse.statusCode, 200, "Response status code should be 200 - OK")
} else {
XCTAssertNotNil(response, "Response should not be nil")
}
expectation.fulfill()
}
sessionTask.resume()
// wait for expectation with timeout
self.waitForExpectations(timeout: 10.0) { (error) in
XCTAssertNil(error, "Web resource is not accessible")
}
// remove all cached response data
URLCacheManager.sharedInstance.removeAllCachedResponses()
let cachedData = URLCacheManager.sharedInstance.cache(for: sessionTask)
XCTAssertNil(cachedData, "Cached data should be nil")
print("Finished cache request")
}
}
| mit | e76d5453d0fedbd0421aa22d9f55c0c0 | 32.246575 | 104 | 0.592501 | 5.417411 | false | true | false | false |
vanyaland/Tagger | Tagger/Sources/PresentationLayer/ViewControllers/Discover/DiscoverTagsViewController.swift | 1 | 12102 | /**
* Copyright (c) 2016 Ivan Magda
*
* 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
// MARK: Types
private enum SectionType: Int, CaseCountable {
case trends
case categories
enum TrendingTags: Int, CaseCountable {
case today
case week
static let sectionTitle = "Trending Tags"
}
enum TagCategories {
static let sectionTitle = "Categories"
}
}
private enum SegueIdentifier: String {
case tagCategoryDetail = "TagCategoryDetail"
}
// MARK: - DiscoverTagsViewController: UIViewController, Alertable -
final class DiscoverTagsViewController: UICollectionViewController, Alertable {
// MARK: Instance Variables
var flickr: IMFlickr!
var persistenceCentral: PersistenceCentral!
private var categories: [Category] {
get {
return persistenceCentral.categories
}
}
private var trendingCategories: [Category] {
get {
return persistenceCentral.trendingCategories
}
}
private var imagesLoadingSet = Set<IndexPath>()
private var numberOfColumns = 2
private var maxNumberOfColumns = 3
// MARK: - UIViewController lifecycle
override func viewDidLoad() {
super.viewDidLoad()
assert(flickr != nil && persistenceCentral != nil)
setup()
}
override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
numberOfColumns += (toInterfaceOrientation.isLandscape ? 1 : -1)
if numberOfColumns > maxNumberOfColumns {
numberOfColumns = maxNumberOfColumns
}
collectionView?.collectionViewLayout.invalidateLayout()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Private
private func setup() {
setupUI()
NotificationCenter.default.addObserver(
self,
selector: #selector(reloadData),
name: NSNotification.Name(rawValue: persistenceCentralDidChangeContentNotification),
object: nil
)
}
}
// MARK: - DiscoverTagsViewController (Actions) -
extension DiscoverTagsViewController {
@objc private func reloadData() {
collectionView!.reloadData()
}
}
// MARK: - DiscoverTagsViewController (UI) -
extension DiscoverTagsViewController {
private func setupUI() {
guard let layout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout else { return }
layout.sectionInset = UIEdgeInsets(top: 15.0, left: 15.0, bottom: 15.0, right: 15.0)
layout.minimumInteritemSpacing = 8.0
layout.minimumLineSpacing = 8.0
if #available(iOS 11.0, *) {
layout.sectionInsetReference = .fromSafeArea
collectionView?.contentInsetAdjustmentBehavior = .always
}
collectionView?.contentInset.top += layout.sectionInset.top
}
private func updateTitleColor(for cell: TagCollectionViewCell) {
cell.title.textColor = cell.imageView.image != nil ? .white : .black
}
}
// MARK: - DiscoverTagsViewController: UICollectionViewDataSource -
extension DiscoverTagsViewController {
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return SectionType.countCases()
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard let section = SectionType(rawValue: section) else { return 0 }
switch section {
case .trends:
return trendingCategories.count
case .categories:
return categories.count
}
}
override func collectionView(_ collectionView: UICollectionView,
cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: TagCollectionViewCell.reuseIdentifier,
for: indexPath
) as! TagCollectionViewCell
configureCell(cell, at: indexPath)
return cell
}
override func collectionView(_ collectionView: UICollectionView,
viewForSupplementaryElementOfKind kind: String,
at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionView.elementKindSectionHeader:
let headerView = collectionView.dequeueReusableSupplementaryView(
ofKind: kind,
withReuseIdentifier: SectionHeaderCollectionReusableView.reuseIdentifier,
for: indexPath
) as! SectionHeaderCollectionReusableView
configureSectionHeaderView(headerView, at: indexPath)
return headerView
default:
fatalError("Unexpected element kind")
}
}
// MARK: Private Helpers
private func configureSectionHeaderView(_ view: SectionHeaderCollectionReusableView,
at indexPath: IndexPath) {
switch SectionType(rawValue: indexPath.section)! {
case .trends:
view.title.text = SectionType.TrendingTags.sectionTitle.uppercased()
case .categories:
view.title.text = SectionType.TagCategories.sectionTitle.uppercased()
}
}
private func configureCell(_ cell: TagCollectionViewCell, at indexPath: IndexPath) {
let category = getCategory(for: indexPath)
cell.title.text = category.name.lowercased()
updateTitleColor(for: cell)
if let image = category.image?.image {
cell.imageView.image = image
updateTitleColor(for: cell)
} else {
guard imagesLoadingSet.contains(indexPath) == false else { return }
imagesLoadingSet.insert(indexPath)
loadImageForCell(at: indexPath)
}
}
private func getCategory(for indexPath: IndexPath) -> Category {
return indexPath.section == SectionType.trends.rawValue
? trendingCategories[indexPath.row]
: categories[indexPath.row]
}
// TODO: If network is unreachable, then don't try to download the image again.
private func loadImageForCell(at indexPath: IndexPath) {
func handleError(_ error: Error) {
print("Failed to load an image. Error: \(error.localizedDescription)")
setImage(nil, toCellAtIndexPath: indexPath)
loadImageForCell(at: indexPath)
UIUtils.showNetworkActivityIndicator()
}
let category = getCategory(for: indexPath)
UIUtils.showNetworkActivityIndicator()
if indexPath.section == SectionType.trends.rawValue {
let period: Period = indexPath.row == SectionType.TrendingTags.today.rawValue ? .day : .week
flickr.api.getTagsHotList(
for: period,
success: {
self.flickr.api.getRandomPhoto(
for: $0.map { $0.content },
success: { self.setImage($0, toCellAtIndexPath: indexPath) },
failure: handleError)
},
failure: handleError)
} else {
flickr.api.getRandomPhoto(
for: [category.name],
success: { self.setImage($0, toCellAtIndexPath: indexPath) },
failure: handleError
)
}
}
private func setImage(_ image: UIImage?, toCellAtIndexPath indexPath: IndexPath) {
imagesLoadingSet.remove(indexPath)
UIUtils.hideNetworkActivityIndicator()
// Persist the image.
if let image = image {
persistenceCentral.setImage(image, to: getCategory(for: indexPath))
}
guard collectionView!.indexPathsForVisibleItems.contains(indexPath) == true else { return }
guard let cell = collectionView!.cellForItem(at: indexPath) as? TagCollectionViewCell else { return }
cell.imageView.image = image
updateTitleColor(for: cell)
}
}
// MARK: - DiscoverTagsViewController: UICollectionViewDelegateFlowLayout -
extension DiscoverTagsViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else {
return CGSize.zero
}
var collectionViewWidth = collectionView.bounds.width
if #available(iOS 11.0, *) {
let insets = collectionView.safeAreaInsets
collectionViewWidth -= (insets.left + insets.right)
}
let sectionInsets = layout.sectionInset
let minimumInteritemSpacing = layout.minimumInteritemSpacing
let remainingWidth = collectionViewWidth
- sectionInsets.left
- CGFloat((numberOfColumns - 1)) * minimumInteritemSpacing
- sectionInsets.right
let width = floor(remainingWidth / CGFloat(numberOfColumns))
return CGSize(width: width, height: width)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
guard collectionView.numberOfItems(inSection: section) > 0 else { return CGSize.zero }
return CGSize(width: collectionView.bounds.width, height: SectionHeaderCollectionReusableView.height)
}
}
// MARK: - DiscoverTagsViewController: UICollectionViewDelegate -
extension DiscoverTagsViewController {
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.deselectItem(at: indexPath, animated: false)
let category = getCategory(for: indexPath)
let flickrApi = flickr.api
switch SectionType(rawValue: indexPath.section)! {
case .trends:
let period = indexPath.row == 0 ? Period.day : Period.week
let hotTagsViewController = FlickrHotTagsViewController(flickrApiClient: flickrApi, period: period, category: category)
hotTagsViewController.persistenceCentral = persistenceCentral
navigationController?.pushViewController(hotTagsViewController, animated: true)
case .categories:
let relatedTagsViewController = FlickrRelatedTagsViewController(flickrApiClient: flickr.api, category: category)
relatedTagsViewController.persistenceCentral = persistenceCentral
navigationController?.pushViewController(relatedTagsViewController, animated: true)
}
}
}
| mit | fbb92e9c73dcd32e5e2b4362b29c772e | 35.125373 | 170 | 0.655016 | 5.69238 | false | false | false | false |
neilpa/Rex | Source/UIKit/UIViewController.swift | 3 | 3125 | //
// UIViewController.swift
// Rex
//
// Created by Rui Peres on 14/04/2016.
// Copyright © 2016 Neil Pankey. All rights reserved.
//
import Result
import ReactiveCocoa
import UIKit
extension UIViewController {
/// Returns a `Signal`, that will be triggered
/// when `self`'s `viewDidDisappear` is called
public var rex_viewDidDisappear: Signal<(), NoError> {
return triggerForSelector(#selector(UIViewController.viewDidDisappear(_:)))
}
/// Returns a `Signal`, that will be triggered
/// when `self`'s `viewWillDisappear` is called
public var rex_viewWillDisappear: Signal<(), NoError> {
return triggerForSelector(#selector(UIViewController.viewWillDisappear(_:)))
}
/// Returns a `Signal`, that will be triggered
/// when `self`'s `viewDidAppear` is called
public var rex_viewDidAppear: Signal<(), NoError> {
return triggerForSelector(#selector(UIViewController.viewDidAppear(_:)))
}
/// Returns a `Signal`, that will be triggered
/// when `self`'s `viewWillAppear` is called
public var rex_viewWillAppear: Signal<(), NoError> {
return triggerForSelector(#selector(UIViewController.viewWillAppear(_:)))
}
private func triggerForSelector(selector: Selector) -> Signal<(), NoError> {
return self
.rac_signalForSelector(selector)
.rex_toTriggerSignal()
}
public typealias DismissingCompletion = (Void -> Void)?
public typealias DismissingInformation = (animated: Bool, completion: DismissingCompletion)?
/// Wraps a viewController's `dismissViewControllerAnimated` function in a bindable property.
/// It mimics the same input as `dismissViewControllerAnimated`: a `Bool` flag for the animation
/// and a `(Void -> Void)?` closure for `completion`.
/// E.g:
/// ```
/// //Dismissed with animation (`true`) and `nil` completion
/// viewController.rex_dismissAnimated <~ aProducer.map { _ in (true, nil) }
/// ```
/// The dismissal observation can be made either with binding (example above)
/// or `viewController.dismissViewControllerAnimated(true, completion: nil)`
public var rex_dismissAnimated: MutableProperty<DismissingInformation> {
let initial: UIViewController -> DismissingInformation = { _ in nil }
let setter: (UIViewController, DismissingInformation) -> Void = { host, dismissingInfo in
guard let unwrapped = dismissingInfo else { return }
host.dismissViewControllerAnimated(unwrapped.animated, completion: unwrapped.completion)
}
let property = associatedProperty(self, key: &dismissModally, initial: initial, setter: setter) { property in
property <~ self.rac_signalForSelector(#selector(UIViewController.dismissViewControllerAnimated(_:completion:)))
.takeUntilBlock { _ in property.value != nil }
.rex_toTriggerSignal()
.map { _ in return nil }
}
return property
}
}
private var dismissModally: UInt8 = 0
| mit | 46934732d56791f45adc0a400308a42f | 39.571429 | 124 | 0.660371 | 5.04685 | false | false | false | false |
quire-io/SwiftyChrono | Sources/Refiners/MergeDateTimeRefiner.swift | 1 | 5464 | //
// MergeDateTimeRefiner.swift
// SwiftyChrono
//
// Created by Jerry Chen on 2/16/17.
// Copyright © 2017 Potix. All rights reserved.
//
import Foundation
class MergeDateTimeRefiner: Refiner {
var PATTERN: String { return "" }
var TAGS: TagUnit { return .none }
override public func refine(text: String, results: [ParsedResult], opt: [OptionType: Int]) -> [ParsedResult] {
var results = results
let resultsLength = results.count
if resultsLength < 2 { return results }
var mergedResults = [ParsedResult]()
var currentResult: ParsedResult?
var previousResult: ParsedResult
var i = 1
while i < resultsLength {
currentResult = results[i]
previousResult = results[i-1]
if isDateOnly(result: previousResult) && isTimeOnly(result: currentResult!) &&
isAbleToMerge(text: text, previousResult: previousResult, currentResult: currentResult!) {
results[i] = mergeResult(refText: text, dateResult: previousResult, timeResult: currentResult!)
currentResult = results[i]
i += 1
continue
} else if isDateOnly(result: currentResult!) && isTimeOnly(result: previousResult) &&
isAbleToMerge(text: text, previousResult: previousResult, currentResult: currentResult!) {
results[i] = mergeResult(refText: text, dateResult: currentResult!, timeResult: previousResult)
currentResult = results[i]
i += 1
continue
}
mergedResults.append(previousResult)
i += 1
}
if let currentResult = currentResult {
mergedResults.append(currentResult)
}
return mergedResults
}
private func isDateOnly(result: ParsedResult) -> Bool {
return !result.start.isCertain(component: .hour)
}
private func isTimeOnly(result: ParsedResult) -> Bool {
return !result.start.isCertain(component: .month) && !result.start.isCertain(component: .weekday)
}
private func isAbleToMerge(text: String, previousResult: ParsedResult, currentResult: ParsedResult) -> Bool {
let (startIndex, endIndex) = sortTwoNumbers(previousResult.index + previousResult.text.count, currentResult.index)
let textBetween = text.substring(from: startIndex, to: endIndex)
return NSRegularExpression.isMatch(forPattern: PATTERN, in: textBetween)
}
private func mergeResult(refText text: String, dateResult: ParsedResult, timeResult: ParsedResult) -> ParsedResult {
var dateResult = dateResult
let beginDate = dateResult.start
let beginTime = timeResult.start
var beginDateTime = beginDate
beginDateTime.assign(.hour, value: beginTime[.hour])
beginDateTime.assign(.minute, value: beginTime[.minute])
beginDateTime.assign(.second, value: beginTime[.second])
if beginTime.isCertain(component: .meridiem) {
beginDateTime.assign(.meridiem, value: beginTime[.meridiem]!)
} else if let meridiem = beginTime[.meridiem], beginDateTime[.meridiem] == nil {
beginDateTime.imply(.meridiem, to: meridiem)
}
if
let meridiem = beginDateTime[.meridiem], meridiem == 1,
let hour = beginDateTime[.hour], hour < 12
{
beginDateTime.assign(.hour, value: hour + 12)
}
if dateResult.end != nil || timeResult.end != nil {
let endDate = dateResult.end ?? dateResult.start
let endTime = timeResult.end ?? timeResult.start
var endDateTime = endDate
endDateTime.assign(.hour, value: endTime[.hour])
endDateTime.assign(.minute, value: endTime[.minute])
endDateTime.assign(.second, value: endTime[.second])
if endTime.isCertain(component: .meridiem) {
endDateTime.assign(.meridiem, value: endTime[.meridiem]!)
} else if beginTime[.meridiem] != nil {
endDateTime.imply(.meridiem, to: endTime[.meridiem])
}
if dateResult.end == nil && endDateTime.date.timeIntervalSince1970 < beginDateTime.date.timeIntervalSince1970 {
// Ex. 9pm - 1am
if endDateTime.isCertain(component: .day) {
endDateTime.assign(.day, value: endDateTime[.day]! + 1)
} else if let day = endDateTime[.day] {
endDateTime.imply(.day, to: day + 1)
}
}
dateResult.end = endDateTime
}
dateResult.start = beginDateTime
let startIndex = min(dateResult.index, timeResult.index)
let endIndex = max(
dateResult.index + dateResult.text.count,
timeResult.index + timeResult.text.count)
dateResult.index = startIndex
dateResult.text = text.substring(from: startIndex, to: endIndex)
for tag in timeResult.tags.keys {
dateResult.tags[tag] = true
}
dateResult.tags[TAGS] = true
return dateResult
}
}
| mit | d7f71f7b325716792932163a8a83a5cb | 34.940789 | 123 | 0.58283 | 4.677226 | false | false | false | false |
google/flatbuffers | swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift | 4 | 766 | import FlatBuffers
import Foundation
func run() {
// create a ByteBuffer(:) from an [UInt8] or Data()
let buf = [] // Get your data
// Get an accessor to the root object inside the buffer.
let monster: Monster = try! getCheckedRoot(byteBuffer: ByteBuffer(bytes: buf))
// let monster: Monster = getRoot(byteBuffer: ByteBuffer(bytes: buf))
let hp = monster.hp
let mana = monster.mana
let name = monster.name // returns an optional string
let pos = monster.pos
let x = pos.x
let y = pos.y
// Get and check if the monster has an equipped item
if monster.equippedType == .weapon {
let _weapon = monster.equipped(type: Weapon.self)
let name = _weapon.name // should return "Axe"
let dmg = _weapon.damage // should return 5
}
}
| apache-2.0 | 5e7f1fbf04cf6a39df0d8366d65f7f1a | 28.461538 | 80 | 0.680157 | 3.773399 | false | false | false | false |
esheppard/travel-lingo | xcode/Travel Lingo/Source/Features/Phrases/Models/TranslationPhrase.swift | 1 | 562 | //
// TranslationPhrase.swift
// Travel Lingo
//
// Created by Elijah Sheppard on 19/04/2016.
// Copyright © 2016 Elijah Sheppard. All rights reserved.
//
import Foundation
class TranslationPhrase
{
let phrase: String
let translation: String
let native: String?
let audioFile: String
init(phrase: String, translation: String, native: String? = nil, audioFile: String)
{
self.phrase = phrase
self.translation = translation
self.native = native
self.audioFile = audioFile
}
}
| gpl-3.0 | 277e1f424ae46dd8b730b4dd45dfd556 | 18.344828 | 87 | 0.639929 | 4.155556 | false | false | false | false |
lunixbochs/project-euler | 001-099/02/2.swift | 1 | 159 | var a = 0, b = 1;
var total = 0;
while b < 4000000 {
if b % 2 == 0 {
total += b;
}
var tmp = a;
a = b;
b += tmp;
}
println(total);
| mit | 8a8ea7f78678c3a706af2e7e6c8bff23 | 13.454545 | 19 | 0.408805 | 2.606557 | false | false | false | false |
CatchChat/Yep | Yep/ViewControllers/Chat/CellNodes/ChatLeftImageCellNode.swift | 1 | 2952 | //
// ChatLeftImageCellNode.swift
// Yep
//
// Created by NIX on 16/7/5.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
import AsyncDisplayKit
class ChatLeftImageCellNode: ChatLeftBaseCellNode {
var tapImageAction: ((node: Previewable) -> Void)?
private let imagePreferredWidth = YepConfig.ChatCell.mediaPreferredWidth
private let imagePreferredHeight = YepConfig.ChatCell.mediaPreferredHeight
private let imagePreferredAspectRatio: CGFloat = 4.0 / 3.0
private lazy var imageMaskView: UIView = {
let imageView = UIImageView()
imageView.image = UIImage(named: "left_tail_image_bubble")
return imageView
}()
lazy var imageNode: ASImageNode = {
let node = ASImageNode()
node.contentMode = .ScaleAspectFill
node.view.maskView = self.imageMaskView
let tapAvatar = UITapGestureRecognizer(target: self, action: #selector(ChatLeftImageCellNode.tapImage(_:)))
node.userInteractionEnabled = true
node.view.addGestureRecognizer(tapAvatar)
return node
}()
private lazy var borderNode: ASImageNode = {
let node = ASImageNode()
node.contentMode = .ScaleAspectFill
let image = UIImage(named: "left_tail_image_bubble_border")?.resizableImageWithCapInsets(UIEdgeInsets(top: 25, left: 27, bottom: 20, right: 20), resizingMode: .Stretch)
node.image = image
return node
}()
override init() {
super.init()
addSubnode(imageNode)
addSubnode(borderNode)
}
private var imageSize: CGSize?
func configure(withMessage message: Message) {
self.user = message.fromFriend
do {
let imageSize = message.fixedImageSize
self.imageSize = imageSize
imageNode.yep_setImageOfMessage(message, withSize: imageSize, tailDirection: .Left, completion: { [weak self] loadingProgress, image in
self?.imageNode.image = image
})
}
}
override func calculateSizeThatFits(constrainedSize: CGSize) -> CGSize {
let height = max(imageSize?.height ?? 0, ChatBaseCellNode.avatarSize.height)
return CGSize(width: constrainedSize.width, height: height + ChatBaseCellNode.verticalPadding)
}
override func layout() {
super.layout()
let x = 15 + ChatBaseCellNode.avatarSize.width + 5
let y = ChatBaseCellNode.topPadding
let origin = CGPoint(x: x, y: y)
var size = self.imageSize ?? CGSize(width: 40, height: 40)
size.width = min(size.width, YepConfig.ChatCell.imageMaxWidth)
imageNode.frame = CGRect(origin: origin, size: size)
imageMaskView.frame = imageNode.bounds
borderNode.frame = imageNode.frame
}
// MARK: Selectors
@objc private func tapImage(sender: UITapGestureRecognizer) {
tapImageAction?(node: self)
}
}
| mit | 0c693984b91db33e8c4def03e833093a | 28.19802 | 176 | 0.660902 | 4.586314 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/Pods/RxGesture/Pod/Classes/GestureFactory.swift | 1 | 2250 | // Copyright (c) RxSwiftCommunity
// 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 RxSwift
import RxCocoa
import ObjectiveC
public typealias Configuration<Gesture> = (Gesture, RxGestureRecognizerDelegate) -> Void
public struct Factory<Gesture: GestureRecognizer> {
public let gesture: Gesture
public init(_ configuration: Configuration<Gesture>?) {
let gesture = Gesture()
let delegate = RxGestureRecognizerDelegate()
objc_setAssociatedObject(
gesture,
&gestureRecognizerStrongDelegateKey,
delegate,
.OBJC_ASSOCIATION_RETAIN_NONATOMIC
)
gesture.delegate = delegate
configuration?(gesture, delegate)
self.gesture = gesture
}
internal func abstracted() -> AnyFactory {
return AnyFactory(self.gesture)
}
}
internal func make<G>(configuration: Configuration<G>? = nil) -> Factory<G> {
return Factory<G>(configuration)
}
public typealias AnyFactory = Factory<GestureRecognizer>
extension Factory where Gesture == GestureRecognizer {
private init<G: GestureRecognizer>(_ gesture: G) {
self.gesture = gesture
}
}
private var gestureRecognizerStrongDelegateKey: UInt8 = 0
| apache-2.0 | 4501ab30431681c5f110469f67e0a7ba | 37.135593 | 88 | 0.729778 | 4.859611 | false | true | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/01138-void.swift | 1 | 753 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func i(c: () -> ()) {
}
class a {
var _ = i() {
class b<h : c, i : c where h.g == i> : a {
}
class b<h, i> {
}
protocol c {
}
struct A<T> {
}
protocol b {
}
struct c {
}
var e: Int -> Int = {
}
let d: Int = { c, b in
}(f, e)
struct d<f : e, g: e where g.h == f.h> {
}
func g<T== F>(f: B<T>) {
}
}
func a() {
for c in 0..<d) {
}
.b =}
}
import Foundation
| apache-2.0 | b78a6b68ba0faf9c7d6b995d2bee069d | 18.307692 | 79 | 0.61089 | 2.698925 | false | false | false | false |
onebytegone/LineKoala | LineKoalaDemo/LineKoalaDemo/DrawingView.swift | 1 | 1241 | //
// DrawingView.swift
// LineKoalaDemo
//
// Created by Ethan Smith on 6/24/15.
// Copyright (c) 2015 Ethan Smith. All rights reserved.
//
import UIKit
import LineKoala
class DrawingView : UIView {
override func drawRect(rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
CGContextSetRGBStrokeColor(ctx, 0.5, 0.5, 0.5, 1.0)
CGContextSetLineWidth(ctx, 4)
// Generate points
let lineKoala = LineKoala()
var points = lineKoala.generateLinePoints(CGPointMake(40, 40), to: CGPointMake(200, 200))
lineKoala.drawLine(points, lineStart: { (origin) -> Void in
CGContextMoveToPoint(ctx, origin.x, origin.y)
}, moveTo: { (point) -> Void in
CGContextAddLineToPoint(ctx, point.x, point.y)
})
CGContextStrokePath(ctx)
// Uncomment for point drawing:
// -----
// let size: CGFloat = 4
// CGContextSetRGBFillColor(ctx, 0.5, 1, 0.5, 1.0)
// let drawPoint = { (point: CGPoint) -> Void in
// CGContextFillEllipseInRect(ctx, CGRectMake(point.x-size/2, point.y-size/2, size, size))
// }
// lineKoala.drawLine(points, lineStart: drawPoint, moveTo: drawPoint)
// Call super
super.drawRect(rect)
}
}
| mit | f62057783384976fb0a39c0875ed26bf | 28.547619 | 99 | 0.63336 | 3.737952 | false | false | false | false |
bykoianko/omim | iphone/Maps/Bookmarks/Categories/Sharing/BookmarksSharingViewController.swift | 1 | 14159 | import SafariServices
@objc
protocol BookmarksSharingViewControllerDelegate: AnyObject {
func didShareCategory()
}
final class BookmarksSharingViewController: MWMTableViewController {
typealias ViewModel = MWMAuthorizationViewModel
@objc var categoryId = MWMFrameworkHelper.invalidCategoryId()
var categoryUrl: URL?
@objc weak var delegate: BookmarksSharingViewControllerDelegate?
private var sharingTags: [MWMTag]?
private var sharingUserStatus: MWMCategoryAuthorType?
private var manager: MWMBookmarksManager {
return MWMBookmarksManager.shared()
}
private var categoryAccessStatus: MWMCategoryAccessStatus? {
guard categoryId != MWMFrameworkHelper.invalidCategoryId() else {
assert(false)
return nil
}
return manager.getCategoryAccessStatus(categoryId)
}
private let kPropertiesSegueIdentifier = "chooseProperties"
private let kTagsControllerIdentifier = "tags"
private let kEditOnWebSegueIdentifier = "editOnWeb"
private let publicSectionIndex = 0
private let privateSectionIndex = 1
private let editOnWebCellIndex = 3
private let rowsInPrivateSection = 2
private var rowsInPublicSection: Int {
return categoryAccessStatus == .public ? 4 : 3
}
@IBOutlet private weak var uploadAndPublishCell: UploadActionCell!
@IBOutlet private weak var getDirectLinkCell: UploadActionCell!
@IBOutlet private weak var editOnWebCell: UITableViewCell!
@IBOutlet private weak var licenseAgreementTextView: UITextView! {
didSet {
let htmlString = String(coreFormat: L("ugc_routes_user_agreement"), arguments: [ViewModel.termsOfUseLink()])
let attributes: [NSAttributedStringKey : Any] = [NSAttributedStringKey.font: UIFont.regular14(),
NSAttributedStringKey.foregroundColor: UIColor.blackSecondaryText()]
licenseAgreementTextView.attributedText = NSAttributedString.string(withHtml: htmlString,
defaultAttributes: attributes)
licenseAgreementTextView.delegate = self
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = L("sharing_options")
configureActionCells()
assert(categoryId != MWMFrameworkHelper.invalidCategoryId(), "We can't share nothing")
guard let categoryAccessStatus = categoryAccessStatus else { return }
switch categoryAccessStatus {
case .local:
break
case .public:
categoryUrl = manager.sharingUrl(forCategoryId: categoryId)
uploadAndPublishCell.cellState = .completed
case .private:
categoryUrl = manager.sharingUrl(forCategoryId: categoryId)
getDirectLinkCell.cellState = .completed
case .other:
break
}
}
func configureActionCells() {
uploadAndPublishCell.config(titles: [ .normal : L("upload_and_publish"),
.inProgress : L("upload_and_publish_progress_text"),
.completed : L("upload_and_publish_success") ],
image: UIImage(named: "ic24PxGlobe"),
delegate: self)
getDirectLinkCell.config(titles: [ .normal : L("upload_and_get_direct_link"),
.inProgress : L("direct_link_progress_text"),
.completed : L("direct_link_success") ],
image: UIImage(named: "ic24PxLink"),
delegate: self)
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
override func numberOfSections(in _: UITableView) -> Int {
return categoryAccessStatus == .public ? 1 : 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case publicSectionIndex:
return rowsInPublicSection
case privateSectionIndex:
return rowsInPrivateSection
default:
return 0
}
}
override func tableView(_ tableView: UITableView,
titleForHeaderInSection section: Int) -> String? {
return section == 0 ? L("public_access") : L("limited_access")
}
override func tableView(_ tableView: UITableView,
willSelectRowAt indexPath: IndexPath) -> IndexPath? {
let cell = tableView.cellForRow(at: indexPath)
if cell == getDirectLinkCell && getDirectLinkCell.cellState != .normal
|| cell == uploadAndPublishCell && uploadAndPublishCell.cellState != .normal {
return nil
}
return indexPath
}
override func tableView(_ tableView: UITableView,
didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let cell = tableView.cellForRow(at: indexPath)
if cell == uploadAndPublishCell {
startUploadAndPublishFlow()
} else if cell == getDirectLinkCell {
uploadAndGetDirectLink()
}
}
func startUploadAndPublishFlow() {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPublic])
performAfterValidation(anchor: uploadAndPublishCell) { [weak self] in
if let self = self {
self.performSegue(withIdentifier: self.kPropertiesSegueIdentifier, sender: self)
}
}
}
func uploadAndPublish() {
guard categoryId != MWMFrameworkHelper.invalidCategoryId(),
let tags = sharingTags,
let userStatus = sharingUserStatus else {
assert(false, "not enough data for public sharing")
return
}
manager.setCategory(categoryId, authorType: userStatus)
manager.setCategory(categoryId, tags: tags)
manager.uploadAndPublishCategory(withId: categoryId, progress: { (progress) in
self.uploadAndPublishCell.cellState = .inProgress
}) { (url, error) in
if let error = error as NSError? {
self.uploadAndPublishCell.cellState = .normal
self.showErrorAlert(error)
} else {
self.uploadAndPublishCell.cellState = .completed
self.categoryUrl = url
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : self.manager.getCategoryTracksCount(self.categoryId),
kStatPoints : self.manager.getCategoryMarksCount(self.categoryId)])
self.tableView.beginUpdates()
self.tableView.deleteSections(IndexSet(arrayLiteral: self.privateSectionIndex), with: .fade)
self.tableView.insertRows(at: [IndexPath(item: self.editOnWebCellIndex,
section: self.publicSectionIndex)],
with: .automatic)
self.tableView.endUpdates()
}
}
}
func uploadAndGetDirectLink() {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatPrivate])
performAfterValidation(anchor: getDirectLinkCell) { [weak self] in
guard let s = self, s.categoryId != MWMFrameworkHelper.invalidCategoryId() else {
assert(false, "categoryId must be valid")
return
}
s.manager.uploadAndGetDirectLinkCategory(withId: s.categoryId, progress: { (progress) in
if progress == .uploadStarted {
s.getDirectLinkCell.cellState = .inProgress
}
}, completion: { (url, error) in
if let error = error as NSError? {
s.getDirectLinkCell.cellState = .normal
s.showErrorAlert(error)
} else {
s.getDirectLinkCell.cellState = .completed
s.categoryUrl = url
s.delegate?.didShareCategory()
Statistics.logEvent(kStatSharingOptionsUploadSuccess, withParameters:
[kStatTracks : s.manager.getCategoryTracksCount(s.categoryId),
kStatPoints : s.manager.getCategoryMarksCount(s.categoryId)])
}
})
}
}
func performAfterValidation(anchor: UIView, action: @escaping MWMVoidBlock) {
if MWMFrameworkHelper.isNetworkConnected() {
signup(anchor: anchor, onComplete: { success in
if success {
action()
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 1])
}
})
} else {
Statistics.logEvent(kStatSharingOptionsError, withParameters: [kStatError : 0])
MWMAlertViewController.activeAlert().presentDefaultAlert(withTitle: L("common_check_internet_connection_dialog_title"),
message: L("common_check_internet_connection_dialog"),
rightButtonTitle: L("downloader_retry"),
leftButtonTitle: L("cancel")) {
self.performAfterValidation(anchor: anchor,
action: action)
}
}
}
func showErrorAlert(_ error: NSError) {
guard error.code == kCategoryUploadFailedCode,
let statusCode = error.userInfo[kCategoryUploadStatusKey] as? Int,
let status = MWMCategoryUploadStatus(rawValue: statusCode) else {
assert(false)
return
}
switch (status) {
case .networkError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 1])
self.showUploadError()
case .serverError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 2])
self.showUploadError()
case .authError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 3])
self.showUploadError()
case .malformedData:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 4])
self.showMalformedDataError()
case .accessError:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 5])
self.showAccessError()
case .invalidCall:
Statistics.logEvent(kStatSharingOptionsUploadError, withParameters: [kStatError : 6])
assert(false, "sharing is not available for paid bookmarks")
}
}
private func showUploadError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("upload_error_toast"))
}
private func showMalformedDataError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("unable_upload_error_subtitle_broken"))
}
private func showAccessError() {
MWMAlertViewController.activeAlert().presentInfoAlert(L("unable_upload_errorr_title"),
text: L("unable_upload_error_subtitle_edited"))
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == kPropertiesSegueIdentifier {
if let vc = segue.destination as? SharingPropertiesViewController {
vc.delegate = self
}
} else if segue.identifier == kEditOnWebSegueIdentifier {
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatEditOnWeb])
if let vc = segue.destination as? EditOnWebViewController {
vc.delegate = self
vc.guideUrl = categoryUrl
}
}
}
}
extension BookmarksSharingViewController: UITextViewDelegate {
func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
let safari = SFSafariViewController(url: URL)
present(safari, animated: true, completion: nil)
return false
}
}
extension BookmarksSharingViewController: UploadActionCellDelegate {
func cellDidPressShareButton(_ cell: UploadActionCell, senderView: UIView) {
guard let url = categoryUrl else {
assert(false, "must provide guide url")
return
}
Statistics.logEvent(kStatSharingOptionsClick, withParameters: [kStatItem : kStatCopyLink])
let message = String(coreFormat: L("share_bookmarks_email_body_link"), arguments: [url.absoluteString])
let shareController = MWMActivityViewController.share(for: nil, message: message) {
_, success, _, _ in
if success {
Statistics.logEvent(kStatSharingLinkSuccess, withParameters: [kStatFrom : kStatSharingOptions])
}
}
shareController?.present(inParentViewController: self, anchorView: senderView)
}
}
extension BookmarksSharingViewController: SharingTagsViewControllerDelegate {
func sharingTagsViewController(_ viewController: SharingTagsViewController, didSelect tags: [MWMTag]) {
navigationController?.popViewController(animated: true)
sharingTags = tags
uploadAndPublish()
}
func sharingTagsViewControllerDidCancel(_ viewController: SharingTagsViewController) {
navigationController?.popViewController(animated: true)
}
}
extension BookmarksSharingViewController: SharingPropertiesViewControllerDelegate {
func sharingPropertiesViewController(_ viewController: SharingPropertiesViewController,
didSelect userStatus: MWMCategoryAuthorType) {
sharingUserStatus = userStatus
let storyboard = UIStoryboard.instance(.sharing)
let tagsController = storyboard.instantiateViewController(withIdentifier: kTagsControllerIdentifier)
as! SharingTagsViewController
tagsController.delegate = self
guard var viewControllers = navigationController?.viewControllers else {
assert(false)
return
}
viewControllers.removeLast()
viewControllers.append(tagsController)
navigationController?.setViewControllers(viewControllers, animated: true)
}
}
extension BookmarksSharingViewController: EditOnWebViewControllerDelegate {
func editOnWebViewControllerDidFinish(_ viewController: EditOnWebViewController) {
dismiss(animated: true)
}
}
| apache-2.0 | 2f2eee871b62cd2f0836b7c461a79c5e | 38.661064 | 125 | 0.666714 | 5.117094 | false | false | false | false |
mokagio/GaugeKit | Example/Example/MainViewController.swift | 3 | 2369 | //
// MainViewController.swift
// SWGauge
//
// Created by Petr Korolev on 21/05/15.
// Copyright (c) 2015 Petr Korolev. All rights reserved.
//
import UIKit
import GaugeKit
class MainViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var allGauges: [Gauge]!
// @IBOutlet var scaleLabel: UILabel!
@IBOutlet var gauge: Gauge!
@IBOutlet var gaugeSmall: Gauge!
@IBOutlet var leftGauge: Gauge!
@IBOutlet var rightGauge: Gauge!
@IBOutlet var lineGauge: Gauge!
@IBAction func sliderChanged(sender: UISlider) {
gauge.rate = CGFloat(sender.value)
gaugeSmall.rate = CGFloat(sender.value)
leftGauge.rate = CGFloat(sender.value)
rightGauge.rate = CGFloat(sender.value)
lineGauge.rate = CGFloat(sender.value)
// scaleLabel.text = "\(sender.value)"
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
@IBAction func animateAction(sender: AnyObject) {
// UIView.beginAnimations(nil, context: nil)
// UIView.setAnimationDuration(5.0)
// for gauge in self.allGauges {
// gauge.rate = gauge.rate == 0.0 ? 10 : 0
// }
// UIView.commitAnimations()
//
UIView.animateWithDuration(NSTimeInterval(5.0), animations: {
() -> Void in
println(self.allGauges.count)
for gauge in self.allGauges {
gauge.rate = gauge.rate == 0.0 ? 10 : 0
// gauge.rate = CGFloat(arc4random() % 10)
}
return
})
}
@IBAction func switchChanged(sender: UISwitch) {
gauge.reverse = sender.on
leftGauge.reverse = sender.on
rightGauge.reverse = sender.on
lineGauge.reverse = sender.on
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | 482d95444ab5ba1df014bf32d7b9e2fb | 26.546512 | 106 | 0.627691 | 4.299456 | false | false | false | false |
antonio081014/LeetCode-CodeBase | Swift/largest-rectangle-in-histogram.swift | 2 | 1819 | /**
* Problem Link: https://leetcode.com/problems/largest-rectangle-in-histogram/
*
* The stack keep the index of incremental heights.
*/
class Solution {
func largestRectangleArea(_ heightsList: [Int]) -> Int {
var heights = heightsList + [0]
var list = [Int]()
var maxA = 0
var index = 0
while index < heights.count {
if list.count == 0 || heights[list.last!] <= heights[index] {
list.append(index)
index += 1
} else {
let h = heights[list.popLast()!]
let w = list.isEmpty ? index : index - list.last! - 1
maxA = max(maxA, w * h)
}
}
return maxA
}
}
/**
* https://leetcode.com/problems/largest-rectangle-in-histogram/
*
*
*/
// Date: Wed Jun 24 12:04:45 PDT 2020
class Solution {
func largestRectangleArea(_ heights: [Int]) -> Int {
guard heights.count > 0 else { return 0 }
var leftBound = Array(repeating: -1, count: heights.count)
for index in 1 ..< heights.count {
var p = index - 1
while p >= 0, heights[p] >= heights[index] {
p = leftBound[p]
}
leftBound[index] = p
}
var rightBound = Array(repeating: heights.count, count: heights.count)
for index in stride(from: heights.count - 2, through: 0, by: -1) {
var p = index + 1
while p < heights.count, heights[p] >= heights[index] {
p = rightBound[p]
}
rightBound[index] = p
}
var maxArea = 0
for index in 0 ..< heights.count {
maxArea = max(maxArea, heights[index] * (rightBound[index] - leftBound[index] - 1))
}
return maxArea
}
}
| mit | cad2a4d0286921f4d1d71faa102b9aa1 | 29.830508 | 95 | 0.515118 | 3.954348 | false | false | false | false |
jingwei-huang1/LayoutKit | LayoutKitSampleApp/Benchmarks/BenchmarkViewController.swift | 3 | 4845 | // Copyright 2016 LinkedIn Corp.
// 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.
import UIKit
/// Runs benchmarks for different kinds of layouts.
class BenchmarkViewController: UITableViewController {
private let reuseIdentifier = "cell"
private let viewControllers: [ViewControllerData] = [
ViewControllerData(title: "UICollectionView UIStack feed", factoryBlock: { viewCount in
if #available(iOS 9.0, *) {
let data = FeedItemData.generate(count: viewCount)
return CollectionViewController<FeedItemUIStackView>(data: data)
} else {
NSLog("UIStackView only supported on iOS 9+")
return nil
}
}),
ViewControllerData(title: "UICollectionView Auto Layout feed", factoryBlock: { viewCount in
let data = FeedItemData.generate(count: viewCount)
return CollectionViewController<FeedItemAutoLayoutView>(data: data)
}),
ViewControllerData(title: "UICollectionView LayoutKit feed", factoryBlock: { viewCount in
let data = FeedItemData.generate(count: viewCount)
return CollectionViewController<FeedItemLayoutKitView>(data: data)
}),
ViewControllerData(title: "UICollectionView Manual Layout feed", factoryBlock: { viewCount in
let data = FeedItemData.generate(count: viewCount)
return CollectionViewController<FeedItemManualView>(data: data)
}),
ViewControllerData(title: "UITableView UIStack feed", factoryBlock: { viewCount in
if #available(iOS 9.0, *) {
let data = FeedItemData.generate(count: viewCount)
return TableViewController<FeedItemUIStackView>(data: data)
} else {
NSLog("UIStackView only supported on iOS 9+")
return nil
}
}),
ViewControllerData(title: "UITableView Auto Layout feed", factoryBlock: { viewCount in
let data = FeedItemData.generate(count: viewCount)
return TableViewController<FeedItemAutoLayoutView>(data: data)
}),
ViewControllerData(title: "UITableView LayoutKit feed", factoryBlock: { viewCount in
let data = FeedItemData.generate(count: viewCount)
return TableViewController<FeedItemLayoutKitView>(data: data)
}),
ViewControllerData(title: "UITableView Manual Layout feed", factoryBlock: { viewCount in
let data = FeedItemData.generate(count: viewCount)
return TableViewController<FeedItemManualView>(data: data)
})
]
convenience init() {
self.init(style: .grouped)
title = "Benchmarks"
}
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: reuseIdentifier)
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewControllers.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath)
cell.textLabel?.text = viewControllers[indexPath.row].title
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let viewControllerData = viewControllers[indexPath.row]
guard let viewController = viewControllerData.factoryBlock(20) else {
return
}
benchmark(viewControllerData)
viewController.title = viewControllerData.title
navigationController?.pushViewController(viewController, animated: true)
}
private func benchmark(_ viewControllerData: ViewControllerData) {
let iterations = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 20, 30, 40, 50, 100]
for i in iterations {
let description = "\(i)\tsubviews\t\(viewControllerData.title)"
Stopwatch.benchmark(description, block: { (stopwatch: Stopwatch) -> Void in
let vc = viewControllerData.factoryBlock(i)
stopwatch.resume()
vc?.view.layoutIfNeeded()
stopwatch.pause()
})
}
}
}
private struct ViewControllerData {
let title: String
let factoryBlock: (_ viewCount: Int) -> UIViewController?
}
| apache-2.0 | cc5ddae89ec103a0614c525b24d995e0 | 40.410256 | 131 | 0.660681 | 5.260586 | false | false | false | false |
Mazy-ma/DemoBySwift | NewsFrameworkDemo/NewsFrameworkDemo/NewsFramework/TopTitlesView.swift | 1 | 7142 | //
// TopTitlesView.swift
// NewsFrameworkDemo
//
// Created by Mazy on 2017/7/25.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
protocol TopTitlesViewDelegate {
func didClickTopTitleView(_ titlesView: TopTitlesView, selectedIndex index : Int)
}
class TopTitlesView: UIView {
// MARK: 对外属性
var delegate: TopTitlesViewDelegate?
fileprivate lazy var scrollView: UIScrollView = {
let scrollView = UIScrollView()
scrollView.frame = self.bounds
scrollView.showsHorizontalScrollIndicator = false
return scrollView
}()
fileprivate lazy var indicatorView: UIView = {
let view = UIView()
view.backgroundColor = UIColor.red
return view
}()
fileprivate var titles: [String]
fileprivate var titleLabels: [UILabel] = [UILabel]()
fileprivate var currentIndex : Int = 0
fileprivate var titleProperty: TitleViewProperty
init(frame: CGRect, titles: [String], titleProperty: TitleViewProperty) {
self.titles = titles
self.titleProperty = titleProperty
super.init(frame: frame)
layoutIfNeeded()
setNeedsLayout()
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension TopTitlesView {
func setupUI() {
backgroundColor = UIColor.white
addSubview(scrollView)
setupTitleLabels()
setupTitleLabelsPosition()
setupIndicatorView()
setShadow()
}
fileprivate func setShadow(){
if !titleProperty.isNeedShadowInBottom { return }
self.layer.shadowColor = UIColor.lightGray.cgColor
self.layer.shadowOpacity = 0.3
self.layer.shadowOffset = CGSize(width: 0, height: 2)
self.layer.shadowRadius = 2
self.layer.masksToBounds = false
// self.layer.magnificationFilter = kCAFilterLinear
}
fileprivate func setupTitleLabels() {
for (index, title) in titles.enumerated() {
let label = UILabel()
label.text = title
label.textAlignment = .center
label.font = titleProperty.font
label.textColor = titleProperty.normalColor
label.tag = 1024 + index
label.isUserInteractionEnabled = true
if index == 0 {
label.textColor = titleProperty.selectedColor
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(titleLabelClick))
label.addGestureRecognizer(tapGesture)
scrollView.addSubview(label)
titleLabels.append(label)
}
}
fileprivate func setupTitleLabelsPosition() {
for (index, label) in titleLabels.enumerated() {
var titleX: CGFloat = 0
var titleW: CGFloat = 0
let titleY: CGFloat = 0
let titleH: CGFloat = bounds.height
if titleProperty.isScrollEnable { // 可以滚动
titleW = label.intrinsicContentSize.width
if index == 0 {
titleX = titleProperty.titleMargin * 0.5
} else {
let preLabel = titleLabels[index - 1]
titleX = preLabel.frame.maxX + titleProperty.titleMargin
}
} else { // 不可滚动
titleW = bounds.width/CGFloat(titles.count)
titleX = titleW * CGFloat(index)
}
label.frame = CGRect(x: titleX, y: titleY, width: titleW, height: titleH)
if titleProperty.isScrollEnable {
scrollView.contentSize = CGSize(width: titleLabels.last!.frame.maxX + titleProperty.titleMargin*0.5, height: 0)
}
}
}
fileprivate func setupIndicatorView() {
indicatorView.isHidden = titleProperty.isHiddenBottomLine
indicatorView.backgroundColor = UIColor.red
if titleProperty.isScrollEnable {
indicatorView.frame = titleLabels.first!.frame
} else {
let titleW: CGFloat = titleLabels.first!.intrinsicContentSize.width
indicatorView.frame.origin.x = (titleLabels.first!.bounds.width-titleW) * 0.5
indicatorView.frame.size.width = titleW
}
indicatorView.frame.size.height = 2
indicatorView.frame.origin.y = bounds.height - 2
scrollView.addSubview(indicatorView)
}
}
extension TopTitlesView {
func titleLabelClick(tapGesture: UITapGestureRecognizer) {
// 获取当前Label
guard let currentLabel = tapGesture.view as? UILabel else { return }
// 如果是重复点击同一个Title,那么直接返回
if (currentLabel.tag-1024 == currentIndex) { return }
// 获取之前的Label
let oldLabel = titleLabels[currentIndex]
// 切换文字的颜色
currentLabel.textColor = UIColor.red
oldLabel.textColor = UIColor.darkGray
currentIndex = currentLabel.tag-1024
delegate?.didClickTopTitleView(self, selectedIndex: currentIndex)
contentViewDidEndScrollAndAdjustLabelPosition()
}
func contentViewDidEndScrollAndAdjustLabelPosition() {
// 0.如果是不需要滚动,则不需要调整中间位置
guard titleProperty.isScrollEnable else { return }
// 1.获取获取目标的Label
let targetLabel = titleLabels[currentIndex]
// 2.计算和中间位置的偏移量
var offSetX = targetLabel.center.x - bounds.width * 0.5
if offSetX < 0 {
offSetX = 0
}
let maxOffset = scrollView.contentSize.width - bounds.width
if offSetX > maxOffset {
offSetX = maxOffset
}
// 3.滚动UIScrollView
UIView.animate(withDuration: 0.25) {
self.scrollView.setContentOffset(CGPoint(x: offSetX, y: 0), animated: false)
}
}
}
// MARK:- 对外暴露的方法
extension TopTitlesView {
func setTitleWithContentOffset(_ contentOffsetX: CGFloat) {
let index: Int = Int(contentOffsetX/bounds.width + 0.5)
currentIndex = index
_ = titleLabels.map({ $0.textColor = titleProperty.normalColor })
let currentLabel = titleLabels[index]
let firstLabel = titleLabels[0]
currentLabel.textColor = titleProperty.selectedColor
var offset: CGFloat = 0
if titleProperty.isScrollEnable {
offset = currentLabel.frame.origin.x + currentLabel.intrinsicContentSize.width/2
} else {
offset = contentOffsetX/CGFloat(self.titles.count) + firstLabel.center.x
}
UIView.animate(withDuration: 0.25) {
self.indicatorView.center.x = offset
self.indicatorView.frame.size.width = currentLabel.intrinsicContentSize.width
}
}
}
| apache-2.0 | 1f4977585dcfb92dc77f38bc82f997ab | 31.078341 | 127 | 0.602643 | 5.289514 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor Payload Library CellViews/PayloadLibraryCellViewProfile.swift | 1 | 5539 | //
// PayloadLibraryCellViewProfile.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright © 2018 Erik Berglund. All rights reserved.
//
import Cocoa
import ProfilePayloads
class PayloadLibraryCellViewProfile: NSTableCellView, PayloadLibraryCellView {
// MARK: -
// MARK: PayloadLibraryCellView Variables
var row = -1
var isMovable = true
var constraintImageViewLeading: NSLayoutConstraint?
var textFieldTitle: NSTextField?
var textFieldDescription: NSTextField?
var imageViewIcon: NSImageView?
var buttonToggle: NSButton?
var buttonToggleIndent: CGFloat = 24
weak var placeholder: PayloadPlaceholder?
weak var profile: Profile?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(payloadPlaceholder: PayloadPlaceholder, profile: Profile?) {
self.placeholder = payloadPlaceholder
self.profile = profile
super.init(frame: NSRect.zero)
// ---------------------------------------------------------------------
// Setup Variables
// ---------------------------------------------------------------------
var constraints = [NSLayoutConstraint]()
// ---------------------------------------------------------------------
// Setup Static View Content
// ---------------------------------------------------------------------
let imageViewIcon = LibraryImageView.icon(image: payloadPlaceholder.icon, width: 31.0, indent: 4.0, constraints: &constraints, cellView: self)
self.imageViewIcon = imageViewIcon
self.buttonToggle = LibraryButton.toggle(image: NSImage(named: NSImage.removeTemplateName), width: 14.0, indent: 5.0, constraints: &constraints, cellView: self)
if payloadPlaceholder.domain != kManifestDomainConfiguration, UserDefaults.standard.bool(forKey: PreferenceKey.payloadLibraryShowDomainAsTitle) {
self.textFieldTitle = LibraryTextField.title(string: payloadPlaceholder.domain, fontSize: 12, fontWeight: NSFont.Weight.bold.rawValue, indent: 6.0, constraints: &constraints, cellView: self)
} else {
self.textFieldTitle = LibraryTextField.title(string: payloadPlaceholder.title, fontSize: 12, fontWeight: NSFont.Weight.bold.rawValue, indent: 6.0, constraints: &constraints, cellView: self)
}
if payloadPlaceholder.payload.updateAvailable {
self.textFieldDescription = LibraryTextField.description(string: "Update Available", constraints: &constraints, topConstant: 0.0, cellView: self)
self.textFieldDescription?.textColor = .systemRed
} else {
self.textFieldDescription = LibraryTextField.description(string: "1 Payload", constraints: &constraints, cellView: self)
self.textFieldDescription?.textColor = .labelColor
}
self.updatePayloadCount(payloadPlaceholder: payloadPlaceholder)
// ---------------------------------------------------------------------
// Setup Static View Content
// ---------------------------------------------------------------------
// ImageView Leading
let constraintImageViewLeading = NSLayoutConstraint(item: imageViewIcon,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1.0,
constant: 5.0)
self.constraintImageViewLeading = constraintImageViewLeading
constraints.append(constraintImageViewLeading)
// TextFieldTitle Top
if let textFieldTitle = self.textFieldTitle {
constraints.append(NSLayoutConstraint(item: textFieldTitle,
attribute: .top,
relatedBy: .equal,
toItem: self,
attribute: .top,
multiplier: 1.0,
constant: 4.5))
}
// ---------------------------------------------------------------------
// Activate Layout Constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(constraints)
}
func updatePayloadCount(payloadPlaceholder: PayloadPlaceholder) {
guard let profile = self.profile else { return }
// let payloadCount = profile?.settings.getPayloadDomainSettingsCount(domain: payloadPlaceholder.domain, type: payloadPlaceholder.payloadType) ?? 1
let payloadCount = profile.settings.settingsCount(forDomainIdentifier: payloadPlaceholder.domainIdentifier, type: payloadPlaceholder.payloadType)
let payloadCountString: String
if payloadCount <= 1 {
payloadCountString = NSLocalizedString("Payload", comment: "")
} else {
payloadCountString = NSLocalizedString("Payloads", comment: "")
}
self.textFieldDescription?.stringValue = "\(payloadCount == 0 ? 1 : payloadCount) \(payloadCountString)"
}
}
| mit | 52acc9571185b83edb9dca7a078bae8b | 46.333333 | 202 | 0.543698 | 6.243517 | false | false | false | false |
juliagaomiller/OnTheMap | OnTheMapJulia/MapVC.swift | 1 | 2802 | //
// MapViewController.swift
// OnTheMapJulia
//
// Created by Julia Miller on 6/4/16.
// Copyright © 2016 Julia Miller. All rights reserved.
//
import Foundation
import UIKit
import MapKit
class MapVC: UIViewController, MKMapViewDelegate {
@IBOutlet weak var map: MKMapView!
var collection: [StudentModel] {
get {
return StudentModel.collection
}
}
override func viewDidLoad() {
self.showPinsOnMap()
map.delegate = self
}
@IBAction func reload(sender: AnyObject) {
loadMapPage()
}
@IBAction func postPersLoc(sender: AnyObject) {
let postVC = storyboard?.instantiateViewControllerWithIdentifier("PostNC")
navigationController?.presentViewController(postVC!, animated: true, completion: nil)
}
@IBAction func logout(sender: AnyObject) {
UdacityClient.sharedInstance.logout()
self.dismissViewControllerAnimated(true, completion: nil)
}
func showPinsOnMap(){
var annotations = [MKPointAnnotation]()
for student in collection {
let annotation = MKPointAnnotation()
let coord = CLLocationCoordinate2DMake(student.lat, student.long)
annotation.coordinate = coord
annotation.title = student.first + " " + student.last
annotation.subtitle = student.url
annotations.append(annotation)
}
map.addAnnotations(annotations)
map.reloadInputViews()
}
func mapView(mapView: MKMapView, viewForAnnotation annotation: MKAnnotation) -> MKAnnotationView? {
let annotationView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: nil)
annotationView.canShowCallout = true
annotationView.rightCalloutAccessoryView = UIButton(type: .DetailDisclosure)
return annotationView
}
func mapView(mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) {
let url = view.annotation!.subtitle!!
UIApplication.sharedApplication().openURL(NSURL(string: url)!)
}
func loadMapPage(){
map.removeAnnotations(map.annotations)
UdacityClient.sharedInstance.getStudentLocations({(success) -> Void in
if (success){
self.showPinsOnMap()
}
else {
let alert = UIAlertController(title: nil, message: "Server error downloading student locations", preferredStyle: .Alert)
let action = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(action)
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
}
| mit | 16cd8044573c1e9d421115a9ed1d54fa | 31.569767 | 136 | 0.641557 | 5.3659 | false | false | false | false |
midoks/Swift-Learning | GitHubStar/GitHubStar/GitHubStar/Controllers/me/user/GsMeScanQrcodeViewController.swift | 1 | 6682 | //
// GsMeScanQrcodeViewController.swift
// GitHubStar
//
// Created by midoks on 16/5/8.
// Copyright © 2016年 midoks. All rights reserved.
//
import UIKit
import AVFoundation
class GsMeScanQrcodeViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
lazy var rdQrcode : MDQrcodeReader = {
return MDQrcodeReader(metadataObjectTypes: [AVMetadataObjectTypeQRCode])
}()
lazy var scanView : MDScanView = {
return MDScanView(frame:self.view.frame)
}()
deinit {
print("GsMeScanQrcodeViewController deinit")
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
if MDQrcodeReader.isCanRun() {
rdQrcode.stopScanning()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.title = sysLang(key: "Scan")
initNav()
initScanView()
initScan()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func initNav(){
// let closeButton = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(self.close))
// self.navigationItem.rightBarButtonItem = closeButton
}
func initScanView(){
self.view.addSubview(self.scanView)
}
func initScan(){
if MDQrcodeReader.isCanRun() {
modalPresentationStyle = .formSheet
rdQrcode.previewLayer.frame = CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height)
rdQrcode.startScanning()
view.layer.insertSublayer(rdQrcode.previewLayer, at: 0)
rdQrcode.completionBlock = { (result: String?) in
self.qRDroid(result: result!)
}
} else {
let alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
}
// 二维码识别处理
func qRDroid(result:String){
print(result)
if self.isHttpWeb(result: result) {
let (r,t,e) = self.isGitHubPage(result: result)
if e {
if t == 1 {//用户follow
let url = GitHubApi.instance.buildUrl( path: "/user/following/" + r )
self.starGithub(url: url)
} else if t == 2 {//repo
let url = GitHubApi.instance.buildUrl( path: "/user/starred/" + r )
self.starGithub(url: url)
}
} else {
self.close()
UIApplication.shared.openURL(NSURL(string: result)! as URL)
}
} else {
let alert = UIAlertController(title: "识别成功", message: result, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: { (UIAlertAction) -> Void in
self.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
func starGithub(url:String){
GitHubApi.instance.webGet(absoluteUrl: url, callback: { (data, response, error) in
if error == nil {
let rep = response as! HTTPURLResponse
let status = rep.allHeaderFields["Status"] as! String
if status == "204 No Content" {
self.showTextWithTime(msg: "已经关注了!", time: 2, callback: {
self.close()
})
} else {
GitHubApi.instance.put(url: url, params: [:], callback: { (data, response, error) in
if error == nil {
let rep = response as! HTTPURLResponse
let status = rep.allHeaderFields["Status"] as! String
if status == "204 No Content" {
self.showTextWithTime(msg: "关注成功!", time: 2, callback: {
self.close()
})
}
}
})
}
}
})
}
// 是否GitHub用户主页
func isGitHubPage(result:String) ->(result:String, type:Int, err:Bool) {
let pattern = "https://(www.)?github.com/(.*[^/])(\\?(.*[^/]))?"
if result =~ pattern {
let tmp_res = result.components(separatedBy: "?")
let tmp2_res = tmp_res[0].components(separatedBy: "/")
if tmp2_res.count == 4 {
let username = tmp2_res[tmp2_res.count - 1]
return (username,1,true)
} else if tmp2_res.count == 5 {
let repo = tmp2_res[tmp2_res.count - 2] + "/" + tmp2_res[tmp2_res.count - 1]
return (repo,2,true)
}
}
return ("",0,false)
}
func isHttpWeb(result:String) -> Bool {
let pattern = "((http[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)"
if result =~ pattern {
return true
}
return false
}
//关闭
func close(){
self.navigationController?.popViewController(animated: true)
}
}
//////////////////正则
infix operator =~
func =~(input:String, pattern:String) -> Bool {
return Regex(pattern: pattern).test(input: input)
}
//正则匹配
class Regex{
let internalExpression:NSRegularExpression
let pattern:String
init(pattern:String){
self.pattern = pattern
self.internalExpression = try! NSRegularExpression(pattern: self.pattern, options: .caseInsensitive)
}
func test(input:String) -> Bool {
let matches = self.internalExpression.matches(in: input, options: NSRegularExpression.MatchingOptions.reportCompletion, range: NSMakeRange(0, input.length))
return matches.count > 0
}
}
| apache-2.0 | 7e55620f888b125930787dc812139128 | 33.212435 | 216 | 0.520521 | 4.482688 | false | false | false | false |
updatra/updatra-ios | Example/Updatra/AppDelegate.swift | 1 | 4255 | //
// AppDelegate.swift
// Updatra
//
// Created by Michael Seid on 12/13/2015.
// Copyright (c) 2015 Michael Seid. All rights reserved.
//
import UIKit
import Updatra
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let updatara = Updatra.sharedInstanceWithAppId("updatra-dev")
updatara.identify(["userId": "40", "email": "[email protected]", "firstName": "Mike"])
let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
UIApplication.sharedApplication().registerForRemoteNotifications()
return true
}
private func convertDeviceTokenToString(deviceToken:NSData) -> String {
// Convert binary Device Token to a String (and remove the <,> and white space charaters).
var deviceTokenStr = deviceToken.description.stringByReplacingOccurrencesOfString(">", withString: "")
deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString("<", withString: "")
deviceTokenStr = deviceTokenStr.stringByReplacingOccurrencesOfString(" ", withString: "")
// Our API returns token in all uppercase, regardless how it was originally sent.
// To make the two consistent, I am uppercasing the token string here.
deviceTokenStr = deviceTokenStr.uppercaseString
return deviceTokenStr
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
let deviceTokenStr = convertDeviceTokenToString(deviceToken)
let updatra = Updatra.sharedInstance()
updatra.addPushDeviceToken(deviceTokenStr)
}
func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
print("Device token for push notifications: FAIL -- ")
print(error.description)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let updatra = Updatra.sharedInstance()
updatra.recievedNotification(userInfo)
}
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.
let updatra = Updatra.sharedInstance()
updatra.showPresence()
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 4580a6c9e0b17db457bd712bd3a280ef | 50.890244 | 285 | 0.738895 | 5.591327 | false | false | false | false |
arslan2012/Lazy-Hackintosh-Image-Generator | LazyHackintoshGenerator/MBR_patch.swift | 1 | 4946 | //
// MBR_patch.swift
// LazyHackintoshGenerator
//
// Created by Arslan Ablikim on 10/5/16.
// Copyright © 2016 Arslan Ablikim. All rights reserved.
//
import RxSwift
func MBR_Patch(OSInstallerPath: String) -> Observable<Void> {
var result: Observable<Int32>
if OSInstallerPath != "" {
result = ShellCommand.shared.run("/bin/cp", ["-f", OSInstallerPath, "\(lazyImageMountPath)/System/Library/PrivateFrameworks/OSInstaller.framework/Versions/A/OSInstaller"], "#Patch osinstaller#", 0)
} else {
result = OSInstaller_Patch(SystemVersion, SystemBuildVersion, "\(lazyImageMountPath.replacingOccurrences(of: " ", with: #"\ "#))/System/Library/PrivateFrameworks/OSInstaller.framework/Versions/A/OSInstaller")
}
if !SystemBuildVersion.SysBuildVerBiggerThan("16A284a") {
result = result.flatMap { _ in
OSInstall_mpkg_Patch(SystemVersion, "\(lazyImageMountPath)/System/Installation/Packages/OSInstall.mpkg")
}
}
return result.map { _ in
viewController!.didReceiveProgress(2)
}
}
func OSInstaller_Patch(_ SystemVersion: String, _ SystemBuildVersion: String, _ OSInstallerPath: String) -> Observable<Int32> {//progress:2%
var patch: Observable<Int32>
if SystemVersion.SysVerBiggerThan("10.11.99") {
if SystemBuildVersion == "16A238m" {// 10.12 PB1+ MBR
patch = ShellCommand.shared.run("/bin/sh", ["-c", #"perl -pi -e 's|\x48\x8B\x78\x28\x48\x85\xFF\x0F\x84\x91\x00\x00\x00\x48|\x48\x8B\x78\x28\x48\x85\xFF\x90\xE9\x91\x00\x00\x00\x48|g' \#(OSInstallerPath)"#], "#Patch osinstaller#", 1)
} else {// 10.12 DB1 only MBR
patch = ShellCommand.shared.run("/bin/sh", ["-c", #"perl -pi -e 's|\x48\x8B\x78\x28\x48\x85\xFF\x0F\x84\x96\x00\x00\x00\x48|\x48\x8B\x78\x28\x48\x85\xFF\x90\xE9\x96\x00\x00\x00\x48|g' \#(OSInstallerPath)"#], "#Patch osinstaller#", 1)
}
} else {// 10.10.x and 10.11.x MBR
patch = ShellCommand.shared.run("/bin/sh", ["-c", #"perl -pi -e 's|\x48\x8B\x78\x28\x48\x85\xFF\x74\x5F\x48\x8B\x85|\x48\x8B\x78\x28\x48\x85\xFF\xEB\x5F\x48\x8B\x85|g' \#(OSInstallerPath)"#], "#Patch osinstaller#", 1)
}
return patch.flatMap { _ in
ShellCommand.shared.sudo("/usr/bin/codesign", ["-f", "-s", "-", OSInstallerPath], "#Patch osinstaller#", 1)
}
}
func OSInstall_mpkg_Patch(_ SystemVersion: String, _ OSInstallPath: String) -> Observable<Int32> {//progress:0%
var patch: Observable<Int32>
patch = ShellCommand.shared.run("/bin/mkdir", ["\(tempFolderPath)/osinstallmpkg"], "#Patch osinstall.mpkg#", 0).flatMap { _ in
ShellCommand.shared.run("/usr/bin/xar", ["-x", "-f", OSInstallPath, "-C", "\(tempFolderPath)/osinstallmpkg"], "#Patch osinstall.mpkg#", 0)
}
if !SystemVersion.SysVerBiggerThan("10.11.99") {// 10.10.x and 10.11.x
patch = patch.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", "s/1024/512/g", "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", "s/var minRam = 2048/var minRam = 1024/g", "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", "s/osVersion=......... osBuildVersion=.......//g", "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", #"/\<installation-check script="installCheckScript()"\/>/d"#, "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", #"/\<volume-check script="volCheckScript()"\/>/d"#, "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}
} else {// 10.12+ and deprecated since DB5/PB4
patch = patch.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", #"/\<installation-check script="InstallationCheck()"\/>/d"#, "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/usr/bin/sed", ["-i", #"''"#, "--", #"/\<volume-check script="VolumeCheck()"\/>/d"#, "\(tempFolderPath)/osinstallmpkg/Distribution"], "#Patch osinstall.mpkg#", 0)
}
}
patch = patch.flatMap { _ in
ShellCommand.shared.run("/bin/rm", [OSInstallPath], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/bin/rm", [#"\#(tempFolderPath)/osinstallmpkg/Distribution''"#], "#Patch osinstall.mpkg#", 0)
}.flatMap { _ in
ShellCommand.shared.run("/usr/bin/xar", ["-cf", OSInstallPath, "."], "#Patch osinstall.mpkg#", 0, "\(tempFolderPath)/osinstallmpkg")
}
return patch
}
| agpl-3.0 | dd637b68a2f73a15d1cd331645a2d3fd | 64.065789 | 245 | 0.625885 | 3.131729 | false | false | false | false |
lorentey/swift | test/IDE/complete_from_clang_framework.swift | 4 | 29079 | // RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=SWIFT_COMPLETIONS | %FileCheck %s -check-prefix=SWIFT_COMPLETIONS
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=FW_UNQUAL_1 > %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_SUB < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_HELPER < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_HELPER_SUB < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_BAR < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_BOTH_FOO_BAR < %t.compl.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_QUAL_FOO_1 > %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_FOO_SUB < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_QUAL_FOO_NEGATIVE < %t.compl.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_QUAL_BAR_1 > %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_QUAL_BAR_1 < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_BAR < %t.compl.txt
// RUN: %FileCheck %s -check-prefix=CLANG_QUAL_BAR_NEGATIVE < %t.compl.txt
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_QUAL_FOO_2 | %FileCheck %s -check-prefix=CLANG_QUAL_FOO_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=FUNCTION_CALL_1 | %FileCheck %s -check-prefix=FUNCTION_CALL_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=FUNCTION_CALL_2 | %FileCheck %s -check-prefix=FUNCTION_CALL_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_STRUCT_MEMBERS_1 | %FileCheck %s -check-prefix=CLANG_STRUCT_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_CLASS_MEMBERS_1 | %FileCheck %s -check-prefix=CLANG_CLASS_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_CLASS_MEMBERS_2 | %FileCheck %s -check-prefix=CLANG_CLASS_MEMBERS_2
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=CLANG_INSTANCE_MEMBERS_1 | %FileCheck %s -check-prefix=CLANG_INSTANCE_MEMBERS_1
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=TYPE_MODULE_QUALIFIER | %FileCheck %s -check-prefix=MODULE_QUALIFIER
// RUN: %target-swift-ide-test -code-completion -source-filename %s -F %S/Inputs/mock-sdk -enable-objc-interop -code-completion-token=EXPR_MODULE_QUALIFIER | %FileCheck %s -check-prefix=MODULE_QUALIFIER
import Foo
// Don't import FooHelper directly in this test!
// import FooHelper
// Framework 'Foo' re-exports the 'FooHelper' framework. Make sure that we get
// completion results for both frameworks.
import Bar
struct SwiftStruct {
var instanceVar : Int
}
// Test that we don't include Clang completions in unexpected places.
func testSwiftCompletions(foo: SwiftStruct) {
foo.#^SWIFT_COMPLETIONS^#
// SWIFT_COMPLETIONS: Begin completions
// SWIFT_COMPLETIONS-NEXT: Keyword[self]/CurrNominal: self[#SwiftStruct#]; name=self
// SWIFT_COMPLETIONS-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// SWIFT_COMPLETIONS-NEXT: End completions
}
// CLANG_FOO: Begin completions
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooEnum1[#FooEnum1#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum1X[#FooEnum1#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooEnum2[#FooEnum2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum2X[#FooEnum2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum2Y[#FooEnum2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooEnum3[#FooEnum3#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum3X[#FooEnum3#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FooEnum3Y[#FooEnum3#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Enum]/OtherModule[Foo]: FooComparisonResult[#FooComparisonResult#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooRuncingOptions[#FooRuncingOptions#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooStruct1[#FooStruct1#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooStruct2[#FooStruct2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[TypeAlias]/OtherModule[Foo]: FooStructTypedef1[#FooStruct2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Struct]/OtherModule[Foo]: FooStructTypedef2[#FooStructTypedef2#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[TypeAlias]/OtherModule[Foo]: FooTypedef1[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: fooIntVar[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFunc1AnonymousParam({#Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFunc3({#(a): Int32#}, {#(b): Float#}, {#(c): Double#}, {#(d): UnsafeMutablePointer<Int32>!#})[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithBlock({#(blk): ((Float) -> Int32)!##(Float) -> Int32#})[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment1()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment2()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment3()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment4()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: fooFuncWithComment5()[#Void#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Protocol]/OtherModule[Foo]: FooProtocolBase[#FooProtocolBase#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Protocol]/OtherModule[Foo]: FooProtocolDerived[#FooProtocolDerived#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Class]/OtherModule[Foo]: FooClassBase[#FooClassBase#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[Class]/OtherModule[Foo]: FooClassDerived[#FooClassDerived#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_1[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_2[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_3[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_4[#UInt32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_5[#UInt64#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_REDEF_1[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[GlobalVar]/OtherModule[Foo]: FOO_MACRO_REDEF_2[#Int32#]{{; name=.+$}}
// CLANG_FOO-DAG: Decl[FreeFunction]/OtherModule[Foo]: theLastDeclInFoo()[#Void#]{{; name=.+$}}
// CLANG_FOO: End completions
// CLANG_FOO_SUB: Begin completions
// CLANG_FOO_SUB-DAG: Decl[FreeFunction]/OtherModule[Foo.FooSub]: fooSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[Struct]/OtherModule[Foo.FooSub]: FooSubEnum1[#FooSubEnum1#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: FooSubEnum1X[#FooSubEnum1#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: FooSubEnum1Y[#FooSubEnum1#]{{; name=.+$}}
// CLANG_FOO_SUB-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: FooSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_FOO_SUB: End completions
// CLANG_FOO_HELPER: Begin completions
// CLANG_FOO_HELPER-DAG: Decl[FreeFunction]/OtherModule[FooHelper]: fooHelperFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO_HELPER-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: FooHelperUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_FOO_HELPER-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: FooHelperUnnamedEnumeratorA2[#Int#]{{; name=.+$}}
// CLANG_FOO_HELPER: End completions
// CLANG_FOO_HELPER_SUB: Begin completions
// CLANG_FOO_HELPER_SUB-DAG: Decl[FreeFunction]/OtherModule[FooHelper.FooHelperSub]: fooHelperSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[Struct]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubEnum1[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubEnum1X[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubEnum1Y[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: FooHelperSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_FOO_HELPER_SUB: End completions
// CLANG_BAR: Begin completions
// CLANG_BAR-DAG: Decl[FreeFunction]/OtherModule[Bar]: barFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[Class]/OtherModule[Bar]: BarForwardDeclaredClass[#BarForwardDeclaredClass#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[Struct]/OtherModule[Bar]: BarForwardDeclaredEnum[#BarForwardDeclaredEnum#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[GlobalVar]/OtherModule[Bar]: BarForwardDeclaredEnumValue[#BarForwardDeclaredEnum#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[GlobalVar]/OtherModule[Bar]: BAR_MACRO_1[#Int32#]{{; name=.+$}}
// CLANG_BAR-DAG: Decl[Struct]/OtherModule[Bar]: SomeItemSet[#SomeItemSet#]
// CLANG_BAR-DAG: Decl[TypeAlias]/OtherModule[Bar]: SomeEnvironment[#SomeItemSet#]
// CLANG_BAR: End completions
// CLANG_BOTH_FOO_BAR: Begin completions
// CLANG_BOTH_FOO_BAR-DAG: Decl[FreeFunction]/OtherModule[{{(Foo|Bar)}}]: redeclaredInMultipleModulesFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_BOTH_FOO_BAR: End completions
// CLANG_QUAL_FOO_NEGATIVE-NOT: bar
// CLANG_QUAL_FOO_NEGATIVE-NOT: :{{.*}}Bar
// CLANG_QUAL_FOO_NEGATIVE-NOT: BAR
// CLANG_QUAL_BAR_NEGATIVE-NOT: foo
// CLANG_QUAL_BAR_NEGATIVE-NOT: :{{.*}}Foo
// CLANG_QUAL_BAR_NEGATIVE-NOT: FOO
func testClangModule() {
#^FW_UNQUAL_1^#
}
func testCompleteModuleQualifiedFoo1() {
Foo.#^CLANG_QUAL_FOO_1^#
}
func testCompleteModuleQualifiedFoo2() {
Foo#^CLANG_QUAL_FOO_2^#
// If the number of results below changes, then you need to add a result to the
// list below.
// CLANG_QUAL_FOO_2: Begin completions, 76 items
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassBase[#FooClassBase#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassDerived[#FooClassDerived#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .ClassWithInternalProt[#ClassWithInternalProt#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: ._InternalStruct[#_InternalStruct#]
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassPropertyOwnership[#FooClassPropertyOwnership#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: ._internalTopLevelFunc()[#Void#]
// CLANG_QUAL_FOO_2-DAG: Decl[Enum]/OtherModule[Foo]: .FooComparisonResult[#FooComparisonResult#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFunc1AnonymousParam({#Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFunc3({#(a): Int32#}, {#(b): Float#}, {#(c): Double#}, {#(d): UnsafeMutablePointer<Int32>!#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncNoreturn1()[#Never#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncNoreturn2()[#Never#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithBlock({#(blk): ((Float) -> Int32)!##(Float) -> Int32#})[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithFunctionPointer({#(fptr): ((Float) -> Int32)!##(Float) -> Int32#})[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment1()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment2()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment3()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment4()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .fooFuncWithComment5()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[FooHelper]: .fooHelperFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[FooHelper.FooHelperSub]: .fooHelperSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo.FooSub]: .fooSubFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[{{(Foo|Bar)}}]: .redeclaredInMultipleModulesFunc1({#(a): Int32#})[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[FreeFunction]/OtherModule[Foo]: .theLastDeclInFoo()[#Void#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_1[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_2[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_3[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_4[#UInt32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_5[#UInt64#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_6[#typedef_int_t#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_7[#typedef_int_t#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_OR[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_AND[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_REDEF_1[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FOO_MACRO_REDEF_2[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum1X[#FooEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum2X[#FooEnum2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum2Y[#FooEnum2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum3X[#FooEnum3#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .FooEnum3Y[#FooEnum3#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubEnum1X[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubEnum1Y[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: .FooHelperUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[FooHelper]: .FooHelperUnnamedEnumeratorA2[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: .FooSubEnum1X[#FooSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: .FooSubEnum1Y[#FooSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo.FooSub]: .FooSubUnnamedEnumeratorA1[#Int#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[GlobalVar]/OtherModule[Foo]: .fooIntVar[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Protocol]/OtherModule[Foo]: ._InternalProt[#_InternalProt#]
// CLANG_QUAL_FOO_2-DAG: Decl[Protocol]/OtherModule[Foo]: .FooProtocolBase[#FooProtocolBase#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Protocol]/OtherModule[Foo]: .FooProtocolDerived[#FooProtocolDerived#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooEnum1[#FooEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooEnum2[#FooEnum2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooEnum3[#FooEnum3#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[FooHelper.FooHelperSub]: .FooHelperSubEnum1[#FooHelperSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooRuncingOptions[#FooRuncingOptions#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooStruct1[#FooStruct1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooStruct2[#FooStruct2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo]: .FooStructTypedef2[#FooStructTypedef2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Struct]/OtherModule[Foo.FooSub]: .FooSubEnum1[#FooSubEnum1#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[TypeAlias]/OtherModule[Foo]: .FooStructTypedef1[#FooStruct2#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooUnavailableMembers[#FooUnavailableMembers#]
// CLANG_QUAL_FOO_2-DAG: Decl[TypeAlias]/OtherModule[Foo]: .FooTypedef1[#Int32#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooCFType[#FooCFType#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooRepeatedMembers[#FooRepeatedMembers#]{{; name=.+$}}
// CLANG_QUAL_FOO_2-DAG: Decl[Class]/OtherModule[Foo]: .FooClassWithClassProperties[#FooClassWithClassProperties#];
// CLANG_QUAL_FOO_2-DAG: Decl[Enum]/OtherModule[Foo]: .SCNFilterMode[#SCNFilterMode#];
// CLANG_QUAL_FOO_2: End completions
}
func testCompleteModuleQualifiedBar1() {
Bar.#^CLANG_QUAL_BAR_1^#
// If the number of results below changes, this is an indication that you need
// to add a result to the appropriate list. Do not just bump the number!
// CLANG_QUAL_BAR_1: Begin completions, 8 items
}
func testCompleteFunctionCall1() {
fooFunc1#^FUNCTION_CALL_1^#
// FUNCTION_CALL_1: Begin completions
// FUNCTION_CALL_1-NEXT: Decl[FreeFunction]/OtherModule[Foo]: ({#(a): Int32#})[#Int32#]{{; name=.+$}}
// FUNCTION_CALL_1-NEXT: Keyword[self]/CurrNominal: .self[#(Int32) -> Int32#]; name=self
// FUNCTION_CALL_1-NEXT: End completions
}
func testCompleteFunctionCall2() {
fooFunc1AnonymousParam#^FUNCTION_CALL_2^#
// FUNCTION_CALL_2: Begin completions
// FUNCTION_CALL_2-NEXT: Decl[FreeFunction]/OtherModule[Foo]: ({#Int32#})[#Int32#]{{; name=.+$}}
// FUNCTION_CALL_2-NEXT: Keyword[self]/CurrNominal: .self[#(Int32) -> Int32#]; name=self
// FUNCTION_CALL_2-NEXT: End completions
}
func testCompleteStructMembers1() {
FooStruct1#^CLANG_STRUCT_MEMBERS_1^#
// CLANG_STRUCT_MEMBERS_1: Begin completions
// CLANG_STRUCT_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ()[#FooStruct1#]{{; name=.+$}}
// CLANG_STRUCT_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ({#x: Int32#}, {#y: Double#})[#FooStruct1#]{{; name=.+$}}
// CLANG_STRUCT_MEMBERS_1-NEXT: Keyword[self]/CurrNominal: .self[#FooStruct1.Type#]; name=self
// CLANG_STRUCT_MEMBERS_1-NEXT: Keyword/CurrNominal: .Type[#FooStruct1.Type#]; name=Type
// CLANG_STRUCT_MEMBERS_1-NEXT: End completions
}
func testCompleteClassMembers1() {
FooClassBase#^CLANG_CLASS_MEMBERS_1^#
// FIXME: do we want to show curried instance functions for Objective-C classes?
// CLANG_CLASS_MEMBERS_1: Begin completions
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFunc0({#(self): FooClassBase#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseInstanceFunc1({#(anObject): Any!#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFunc1({#(self): FooClassBase#})[#(Any?) -> FooClassBase?#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ()[#FooClassBase!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ({#float: Float#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseInstanceFuncOverridden()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFuncOverridden({#(self): FooClassBase#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .fooBaseClassFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[Constructor]/CurrNominal: ({#(x): Int32#})[#FooClassBase!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: ._internalMeth3()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: ._internalMeth3({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: ._internalMeth2()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: ._internalMeth2({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: .nonInternalMeth()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .nonInternalMeth({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[StaticMethod]/CurrNominal: ._internalMeth1()[#Any!#]
// CLANG_CLASS_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: ._internalMeth1({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_1-NEXT: Keyword[self]/CurrNominal: .self[#FooClassBase.Type#]; name=self
// CLANG_CLASS_MEMBERS_1-NEXT: Keyword/CurrNominal: .Type[#FooClassBase.Type#]; name=Type
// CLANG_CLASS_MEMBERS_1-NEXT: End completions
}
func testCompleteClassMembers2() {
FooClassDerived#^CLANG_CLASS_MEMBERS_2^#
// CLANG_CLASS_MEMBERS_2: Begin completions
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(self): FooClassDerived#})[#(Int32) -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc2({#(self): FooClassDerived#})[#(Int32, withB: Int32) -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFuncOverridden({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/CurrNominal: .fooClassFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[Constructor]/CurrNominal: ()[#FooClassDerived!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[Constructor]/CurrNominal: ({#float: Float#})[#FooClassDerived!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFunc({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation1({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation2({#(self): FooClassDerived#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/CurrNominal: .fooProtoClassFunc()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc0({#(self): FooClassBase#})[#() -> Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseInstanceFunc1({#(anObject): Any!#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc1({#(self): FooClassBase#})[#(Any?) -> FooClassBase?#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseInstanceFuncOverridden()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .fooBaseClassFunc0()[#Void#]{{; name=.+$}}
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: ._internalMeth3()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: ._internalMeth3({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: ._internalMeth2()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: ._internalMeth2({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: .nonInternalMeth()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: .nonInternalMeth({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[StaticMethod]/Super: ._internalMeth1()[#Any!#]
// CLANG_CLASS_MEMBERS_2-NEXT: Decl[InstanceMethod]/Super: ._internalMeth1({#(self): FooClassBase#})[#() -> Any?#]
// CLANG_CLASS_MEMBERS_2-NEXT: Keyword[self]/CurrNominal: .self[#FooClassDerived.Type#]; name=self
// CLANG_CLASS_MEMBERS_2-NEXT: Keyword/CurrNominal: .Type[#FooClassDerived.Type#]; name=Type
// CLANG_CLASS_MEMBERS_2-NEXT: End completions
}
func testCompleteInstanceMembers1(fooObject: FooClassDerived) {
fooObject#^CLANG_INSTANCE_MEMBERS_1^#
// CLANG_INSTANCE_MEMBERS_1: Begin completions
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooProperty1[#Int32#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooProperty2[#Int32#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceVar]/CurrNominal: .fooProperty3[#Int32#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc1({#(a): Int32#})[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooInstanceFunc2({#(a): Int32#}, {#withB: Int32#})[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooBaseInstanceFuncOverridden()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFunc()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation1()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/CurrNominal: .fooProtoFuncWithExtraIndentation2()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc0()[#Void#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: .fooBaseInstanceFunc1({#(anObject): Any!#})[#FooClassBase!#]{{; name=.+$}}
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: ._internalMeth3()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: ._internalMeth2()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: .nonInternalMeth()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NEXT: Decl[InstanceMethod]/Super: ._internalMeth1()[#Any!#]
// CLANG_INSTANCE_MEMBERS_1-NOT: Instance
}
// Check the FooHelper module is suggested even though it's not imported directly
func testExportedModuleCompletion() -> #^TYPE_MODULE_QUALIFIER^# {
let x = #^EXPR_MODULE_QUALIFIER^#
// MODULE_QUALIFIER: Begin completions
// MODULE_QUALIFIER-DAG: Decl[Module]/None: swift_ide_test[#Module#]; name=swift_ide_test
// MODULE_QUALIFIER-DAG: Decl[Module]/None: Swift[#Module#]; name=Swift
// MODULE_QUALIFIER-DAG: Decl[Module]/None: Foo[#Module#]; name=Foo
// MODULE_QUALIFIER-DAG: Decl[Module]/None: FooHelper[#Module#]; name=FooHelper
// MODULE_QUALIFIER-DAG: Decl[Module]/None: Bar[#Module#]; name=Bar
// MODULE_QUALIFIER: End completions
}
| apache-2.0 | d668870934ad76e1548c4d8368d9310e | 82.320917 | 213 | 0.687231 | 3.615892 | false | true | false | false |
icetime17/CSSwiftExtension | Sources/UIKit+CSExtension/UICollectionView+CSExtension.swift | 1 | 4271 | //
// UICollectionView+CSExtension.swift
// CSSwiftExtension
//
// Created by Chris Hu on 17/1/3.
// Copyright © 2017年 com.icetime17. All rights reserved.
//
import UIKit
public extension CSSwift where Base: UICollectionView {
// number of all items
var numberOfAllItems: Int {
var itemCount = 0
for section in 0..<base.numberOfSections {
itemCount += base.numberOfItems(inSection: section)
}
return itemCount
}
var firstIndexPath: IndexPath? {
let numberOfSections = base.numberOfSections
if numberOfSections == 0 {
return nil
}
let numberOfItemsOfFirstSection = base.numberOfItems(inSection: 0)
if numberOfItemsOfFirstSection == 0 {
return nil
}
return IndexPath(item: 0, section: 0)
}
var lastIndexPath: IndexPath? {
let numberOfSections = base.numberOfSections
if numberOfSections == 0 {
return nil
}
let numberOfItemsOfLastSection = base.numberOfItems(inSection: numberOfSections - 1)
if numberOfItemsOfLastSection == 0 {
return nil
}
return IndexPath(item: numberOfItemsOfLastSection - 1, section: numberOfSections - 1)
}
}
public extension CSSwift where Base: UICollectionView {
func scrollToFirstCell(scrollPosition: UICollectionView.ScrollPosition,
animated: Bool,
completion: CS_ClosureWithBool? = nil) {
let numberOfSections = base.numberOfSections
if numberOfSections == 0 {
if let completion = completion {
completion(false)
}
return
}
let numberOfItemsOfFirstSection = base.numberOfItems(inSection: 0)
if numberOfItemsOfFirstSection == 0 {
if let completion = completion {
completion(false)
}
return
}
let firstIndexPath = IndexPath(item: 0, section: 0)
base.scrollToItem(at: firstIndexPath, at: scrollPosition, animated: animated)
if let completion = completion {
completion(true)
}
}
func scrollToLastCell(scrollPosition: UICollectionView.ScrollPosition,
animated: Bool,
completion: CS_ClosureWithBool? = nil) {
let numberOfSections = base.numberOfSections
if numberOfSections == 0 {
if let completion = completion {
completion(false)
}
return
}
let numberOfItemsOfLastSection = base.numberOfItems(inSection: numberOfSections - 1)
if numberOfItemsOfLastSection == 0 {
if let completion = completion {
completion(false)
}
return
}
let lastIndexPath = IndexPath(item: numberOfItemsOfLastSection - 1,
section: numberOfSections - 1)
base.scrollToItem(at: lastIndexPath, at: scrollPosition, animated: animated)
if let completion = completion {
completion(true)
}
}
}
/*
// MARK: - reuse
extension UICollectionViewCell: ReusableView {
}
extension UICollectionViewCell: NibLoadable {
}
/*
public typealias ReusableNibView = ReusableView & NibLoadable
public protocol TestProtocol: ReusableView, NibLoadable {
}
*/
public extension CSSwift where Base: UICollectionView {
func registerNib<T: UICollectionViewCell>(_: T.Type) where T: ReusableView & NibLoadable {
let nib = UINib(nibName: T.nibName, bundle: nil)
base.register(nib, forCellWithReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UICollectionViewCell>(forIndexPath indexPath: IndexPath) -> T where T: ReusableView {
guard let cell = base.dequeueReusableCell(withReuseIdentifier: T.reuseIdentifier, for: indexPath) as? T else {
fatalError("CSSwiftExtension: Could not dequeue cell with identifier \(T.reuseIdentifier)")
}
return cell
}
}
*/
| mit | 4b083f5b569abc396dbe1ba18cdce19d | 29.269504 | 118 | 0.595361 | 5.65298 | false | false | false | false |
AnaghSharma/Ambar | Ambar/AppDelegate.swift | 1 | 1037 | //
// AppDelegate.swift
// Ambar
//
// Created by Anagh Sharma on 12/11/19.
// Copyright © 2019 Anagh Sharma. All rights reserved.
//
import Cocoa
import SwiftUI
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var popover = NSPopover.init()
var statusBar: StatusBarController?
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Create the SwiftUI view that provides the contents
let contentView = ContentView()
// Set the SwiftUI's ContentView to the Popover's ContentViewController
popover.contentViewController = MainViewController()
popover.contentSize = NSSize(width: 360, height: 360)
popover.contentViewController?.view = NSHostingView(rootView: contentView)
// Create the Status Bar Item with the Popover
statusBar = StatusBarController.init(popover)
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
}
| mit | 6438cd32d916ae3307073c22d6d8b919 | 29.470588 | 82 | 0.707529 | 5.20603 | false | false | false | false |
kosua20/PtahRenderer | PtahRenderer/Program.swift | 1 | 2811 | //
// Shaders.swift
// PtahRenderer
//
// Created by Simon Rodriguez on 16/02/2016.
// Copyright © 2016 Simon Rodriguez. All rights reserved.
//
import Foundation
public struct InputVertex {
public let v: Vertex
public let t: UV
public let n: Normal
public init(v iv: Vertex, t it: UV, n ni: Normal){
v = iv
t = it
n = ni
}
}
public struct OutputVertex {
public var v: Point4
public var t: UV
public var n: Normal
public var others : [Scalar]
public init(v iv: Point4, t it: UV, n ni: Normal, others oi: [Scalar]){
v = iv
t = it
n = ni
others = oi
}
}
public struct OutputFace {
public let v0: OutputVertex
public let v1: OutputVertex
public let v2: OutputVertex
public init(v0 iv0: OutputVertex, v1 iv1: OutputVertex, v2 iv2: OutputVertex){
v0 = iv0
v1 = iv1
v2 = iv2
}
}
public struct InputFragment {
public let p: (Int, Int, Float)
public let n: Normal
public let t: UV
public let others: [Scalar]
public init(p ip:(Int, Int, Float), n ni: Normal, t it: UV, others oi: [Scalar]){
p = ip
n = ni
t = it
others = oi
}
}
open class Program {
public var textures: [Texture] = []
public var matrices: [Matrix4] = []
public var points4: [Point4] = []
public var points3: [Point3] = []
public var points2: [Point2] = []
public var scalars: [Scalar] = []
public var buffers: [ScalarTexture] = []
public init(){
}
open func vertexShader(_ input: InputVertex) -> OutputVertex { fatalError("Must Override") }
open func fragmentShader(_ input: InputFragment) -> Color? { fatalError("Must Override") }
public func register(index: Int = -1, value: Texture) { if index < 0 { textures.append(value) } else { textures[index] = value } }
public func register(index: Int = -1, value: Matrix4) { if index < 0 { matrices.append(value) } else { matrices[index] = value } }
public func register(index: Int = -1, value: Point4) { if index < 0 { points4.append(value) } else { points4[index] = value } }
public func register(index: Int = -1, value: Point3) { if index < 0 { points3.append(value) } else { points3[index] = value } }
public func register(index: Int = -1, value: Point2) { if index < 0 { points2.append(value) } else { points2[index] = value } }
public func register(index: Int = -1, value: Scalar) { if index < 0 { scalars.append(value) } else { scalars[index] = value } }
public func register(index: Int = -1, value: ScalarTexture) { if index < 0 { buffers.append(value) } else { buffers[index] = value } }
}
func ==(_ x: OutputVertex, _ y: OutputVertex) -> Bool {
// Ignore 'others' attribute.
return x.v == y.v && x.n == y.n && x.t == y.t
}
func !=(_ x: OutputVertex, _ y: OutputVertex) -> Bool {
// Ignore 'others' attribute.
return x.v != y.v || x.n != y.n || x.t != y.t
}
| mit | 38e0dfd070752e70f1a6456f6094af04 | 22.613445 | 135 | 0.637722 | 2.970402 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/Components/TokenField/TokenizedTextView.swift | 1 | 4881 | //
// Wire
// Copyright (C) 2020 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import UIKit
protocol TokenizedTextViewDelegate: AnyObject {
func tokenizedTextView(_ textView: TokenizedTextView, didTapTextRange range: NSRange, fraction: CGFloat)
func tokenizedTextView(_ textView: TokenizedTextView, textContainerInsetChanged textContainerInset: UIEdgeInsets)
}
// ! Custom UITextView subclass to be used in TokenField.
// ! Shouldn't be used anywhere else.
// TODO: as a inner class of TokenField
class TokenizedTextView: TextView {
weak var tokenizedTextViewDelegate: TokenizedTextViewDelegate?
private lazy var tapSelectionGestureRecognizer: UITapGestureRecognizer = {
return UITapGestureRecognizer(target: self, action: #selector(didTapText(_:)))
}()
convenience init() {
self.init(frame: .zero)
setupGestureRecognizer()
}
private func setupGestureRecognizer() {
tapSelectionGestureRecognizer.delegate = self
addGestureRecognizer(tapSelectionGestureRecognizer)
}
// MARK: - Actions
override var contentOffset: CGPoint {
get {
return super.contentOffset
}
set(contentOffset) {
// Text view require no scrolling in case the content size is not overflowing the bounds
if contentSize.height > bounds.size.height {
super.contentOffset = contentOffset
} else {
super.contentOffset = .zero
}
}
}
override var textContainerInset: UIEdgeInsets {
didSet {
tokenizedTextViewDelegate?.tokenizedTextView(self, textContainerInsetChanged: textContainerInset)
}
}
@objc
private func didTapText(_ recognizer: UITapGestureRecognizer) {
var location = recognizer.location(in: self)
location.x -= textContainerInset.left
location.y -= textContainerInset.top
// Find the character that's been tapped on
var characterIndex: Int = 0
var fraction: CGFloat = 0
withUnsafePointer(to: &fraction) {
characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: UnsafeMutablePointer<CGFloat>(mutating: $0))
}
tokenizedTextViewDelegate?.tokenizedTextView(self, didTapTextRange: NSRange(location: characterIndex, length: 1), fraction: fraction)
}
override func copy(_ sender: Any?) {
let stringToCopy = pasteboardString(from: selectedRange)
super.copy(sender)
UIPasteboard.general.string = stringToCopy
}
override func cut(_ sender: Any?) {
let stringToCopy = pasteboardString(from: selectedRange)
super.cut(sender)
UIPasteboard.general.string = stringToCopy
// To fix the iOS bug
delegate?.textViewDidChange?(self)
}
override func paste(_ sender: Any?) {
super.paste(sender)
// To fix the iOS bug
delegate?.textViewDidChange?(self)
}
// MARK: - Utils
private func pasteboardString(from range: NSRange) -> String? {
// enumerate range of current text, resolving person attachents with user name.
var string = ""
for i in range.location..<NSMaxRange(range) {
guard let nsstring = attributedText?.string as NSString? else {
continue
}
if nsstring.character(at: i) == NSTextAttachment.character {
if let tokenAttachemnt = attributedText?.attribute(.attachment, at: i, effectiveRange: nil) as? TokenTextAttachment {
string += tokenAttachemnt.token.title
if i < NSMaxRange(range) - 1 {
string += ", "
}
}
} else {
string += nsstring.substring(with: NSRange(location: i, length: 1))
}
}
return string
}
}
// MARK: - UIGestureRecognizerDelegate
extension TokenizedTextView: UIGestureRecognizerDelegate {
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
| gpl-3.0 | fc2dd1bd8cfd9bbb9266e9aff02d8bbf | 33.373239 | 178 | 0.662364 | 5.237124 | false | false | false | false |
h-n-y/UICollectionView-TheCompleteGuide | chapter-4/Dimensions/Dimensions/AppDelegate.swift | 1 | 2538 | //
// AppDelegate.swift
// Dimensions
//
// Created by Hans Yelek on 5/1/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let navigationController = UINavigationController(rootViewController: ViewController())
navigationController.navigationBar.barStyle = .Black
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window!.backgroundColor = UIColor.whiteColor()
window!.rootViewController = navigationController
window!.makeKeyAndVisible()
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:.
}
}
| mit | 69462969ff8da96a72c421c62dca2d8b | 45.127273 | 285 | 0.742609 | 5.792237 | false | false | false | false |
DanielZakharin/Shelfie | Shelfie/Pods/PieCharts/PieCharts/Core/Chart/PieChart.swift | 2 | 8359 | //
// PieChart.swift
// PieChart2
//
// Created by ischuetz on 06/06/16.
// Copyright © 2016 Ivan Schütz. All rights reserved.
//
import UIKit
@IBDesignable open class PieChart: UIView {
// MARK: - Settings
/// Inner radius of slices - set this to 0 for "no gap".
@IBInspectable public var innerRadius: CGFloat = 50
/// Outer radius of slices.
@IBInspectable public var outerRadius: CGFloat = 100
/// Stroke (border) color of slices.
@IBInspectable public var strokeColor: UIColor = UIColor.black
/// Stroke (border) width of slices.
@IBInspectable public var strokeWidth: CGFloat = 0
/// Pt that will be added to (inner/outer)radius of slice when selecting it.
@IBInspectable public var selectedOffset: CGFloat = 30
/// Duration it takes to slices to expand.
@IBInspectable public var animDuration: Double = 0.5
/// Start angle of chart, in degrees, clockwise. 0 is 3 o'clock, 90 is 6 o'clock, etc.
@IBInspectable public var referenceAngle: CGFloat = 0 {
didSet {
for layer in layers {
layer.clear()
}
let delta = (referenceAngle - oldValue).degreesToRadians
for slice in slices {
slice.view.angles = (slice.view.startAngle + delta, slice.view.endAngle + delta)
}
for slice in slices {
slice.view.present(animated: false)
}
}
}
var animated: Bool {
return animDuration > 0
}
// MARK: -
public fileprivate(set) var container: CALayer = CALayer()
fileprivate var slices: [PieSlice] = []
public var models: [PieSliceModel] = [] {
didSet {
if oldValue.isEmpty {
slices = generateSlices(models)
showSlices()
}
}
}
public weak var delegate: PieChartDelegate?
public var layers: [PieChartLayer] = [] {
didSet {
for layer in layers {
layer.chart = self
}
}
}
public var totalValue: Double {
return models.reduce(0){$0 + $1.value}
}
public override init(frame: CGRect) {
super.init(frame: frame)
sharedInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
sharedInit()
}
private func sharedInit() {
layer.addSublayer(container)
container.frame = bounds
}
fileprivate func generateSlices(_ models: [PieSliceModel]) -> [PieSlice] {
var slices: [PieSlice] = []
var lastEndAngle: CGFloat = 0
for (index, model) in models.enumerated() {
let (newEndAngle, slice) = generateSlice(model: model, index: index, lastEndAngle: lastEndAngle, totalValue: totalValue)
slices.append(slice)
lastEndAngle = newEndAngle
}
return slices
}
fileprivate func generateSlice(model: PieSliceModel, index: Int, lastEndAngle: CGFloat, totalValue: Double) -> (CGFloat, PieSlice) {
let percentage = 1 / (totalValue / model.value)
let angle = (Double.pi * 2) * percentage
let newEndAngle = lastEndAngle + CGFloat(angle)
let data = PieSliceData(model: model, id: index, percentage: percentage)
let slice = PieSlice(data: data, view: PieSliceLayer(color: model.color, startAngle: lastEndAngle, endAngle: newEndAngle, animDelay: 0, center: bounds.center))
slice.view.frame = bounds
slice.view.sliceData = data
slice.view.innerRadius = innerRadius
slice.view.outerRadius = outerRadius
slice.view.selectedOffset = selectedOffset
slice.view.animDuration = animDuration
slice.view.strokeColor = strokeColor
slice.view.strokeWidth = strokeWidth
slice.view.referenceAngle = referenceAngle.degreesToRadians
slice.view.sliceDelegate = self
return (newEndAngle, slice)
}
fileprivate func showSlices() {
for slice in slices {
container.addSublayer(slice.view)
slice.view.rotate(angle: slice.view.referenceAngle)
slice.view.present(animated: animated)
}
}
override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
if let touch = touches.first {
let point = touch.location(in: self)
if let slice = (slices.filter{$0.view.contains(point)}).first {
slice.view.selected = !slice.view.selected
}
}
}
public func insertSlice(index: Int, model: PieSliceModel) {
guard index < slices.count else {print("Out of bounds index: \(index), slices count: \(slices.count), exit"); return}
for layer in layers {
layer.clear()
}
func wrap(angle: CGFloat) -> CGFloat {
return angle.truncatingRemainder(dividingBy: CGFloat.pi * 2)
}
let newSlicePercentage = 1 / ((totalValue + model.value) / model.value)
let remainingPercentage = 1 - newSlicePercentage
let currentSliceAtIndexEndAngle = index == 0 ? 0 : wrap(angle: slices[index - 1].view.endAngle)
let currentSliceAfterIndeStartAngle = index == 0 ? 0 : wrap(angle: slices[index].view.startAngle)
var offset = CGFloat.pi * 2 * CGFloat(newSlicePercentage)
var lastEndAngle = currentSliceAfterIndeStartAngle + offset
let (_, slice) = generateSlice(model: model, index: index, lastEndAngle: currentSliceAtIndexEndAngle, totalValue: model.value + totalValue)
container.addSublayer(slice.view)
slice.view.rotate(angle: slice.view.referenceAngle)
slice.view.presentEndAngle(angle: slice.view.startAngle, animated: false)
slice.view.present(animated: animated)
let slicesToAdjust = Array(slices[index..<slices.count]) + Array(slices[0..<index])
models.insert(model, at: index)
slices.insert(slice, at: index)
for (index, slice) in slices.enumerated() {
slice.data.id = index
}
for slice in slicesToAdjust {
let currentAngle = slice.view.endAngle - slice.view.startAngle
let newAngle = currentAngle * CGFloat(remainingPercentage)
let angleDelta = newAngle - currentAngle
let start = lastEndAngle < slice.view.startAngle ? CGFloat.pi * 2 + lastEndAngle : lastEndAngle
offset = offset + angleDelta
var end = slice.view.endAngle + offset
end = end.truncateDefault() < slice.view.endAngle.truncateDefault() ? CGFloat.pi * 2 + end : end
slice.view.angles = (start, end)
lastEndAngle = wrap(angle: end)
slice.data.percentage = 1 / (totalValue / slice.data.model.value)
}
}
public func removeSlices() {
for slice in slices {
slice.view.removeFromSuperlayer()
}
slices = []
}
open override func prepareForInterfaceBuilder() {
animDuration = 0
strokeWidth = 1
strokeColor = UIColor.lightGray
let models = (0..<6).map {_ in
PieSliceModel(value: 2, color: UIColor.clear)
}
self.models = models
}
}
extension PieChart: PieSliceDelegate {
public func onStartAnimation(slice: PieSlice) {
for layer in layers {
layer.onStartAnimation(slice: slice)
}
delegate?.onStartAnimation(slice: slice)
}
public func onEndAnimation(slice: PieSlice) {
for layer in layers {
layer.onEndAnimation(slice: slice)
}
delegate?.onEndAnimation(slice: slice)
}
public func onSelected(slice: PieSlice, selected: Bool) {
for layer in layers {
layer.onSelected(slice: slice, selected: selected)
}
delegate?.onSelected(slice: slice, selected: selected)
}
}
| gpl-3.0 | 5954b5f1b13c18f542060060a85dc487 | 31.391473 | 167 | 0.583224 | 4.772701 | false | false | false | false |
tristanhimmelman/HidingNavigationBar | HidingNavigationBarSample/HidingNavigationBarSample/HidingNavTabViewController.swift | 1 | 2716 | //
// TableViewController.swift
// HidingNavigationBarSample
//
// Created by Tristan Himmelman on 2015-05-01.
// Copyright (c) 2015 Tristan Himmelman. All rights reserved.
//
import UIKit
class HidingNavTabViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
let identifier = "cell"
var hidingNavBarManager: HidingNavigationBarManager?
var tableView: UITableView!
var toolbar: UIToolbar!
override func viewDidLoad() {
super.viewDidLoad()
tableView = UITableView(frame: view.bounds)
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: identifier)
view.addSubview(tableView)
let cancelButton = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(HidingNavTabViewController.cancelButtonTouched))
navigationItem.leftBarButtonItem = cancelButton
hidingNavBarManager = HidingNavigationBarManager(viewController: self, scrollView: tableView)
if let tabBar = navigationController?.tabBarController?.tabBar {
hidingNavBarManager?.manageBottomBar(tabBar)
tabBar.barTintColor = UIColor(white: 230/255, alpha: 1)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
hidingNavBarManager?.viewWillAppear(animated)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
hidingNavBarManager?.viewDidLayoutSubviews()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
hidingNavBarManager?.viewWillDisappear(animated)
}
@objc func cancelButtonTouched(){
navigationController?.dismiss(animated: true, completion: nil)
}
// MARK: UITableViewDelegate
func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
hidingNavBarManager?.shouldScrollToTop()
return true
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 100
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath)
// Configure the cell...
cell.textLabel?.text = "row \((indexPath as NSIndexPath).row)"
cell.selectionStyle = UITableViewCellSelectionStyle.none
return cell
}
}
| mit | ee8b4478c8ff5955870c10d7561383cb | 30.218391 | 149 | 0.745214 | 4.974359 | false | false | false | false |
exevil/Keys-For-Sketch | Source/Support/Const.swift | 1 | 6567 | //
// Constants.swift
// KeysForSketch
//
// Created by Vyacheslav Dubovitsky on 19/04/2017.
// Copyright © 2017 Vyacheslav Dubovitsky. All rights reserved.
//
public struct Const {
/// Image names.
public struct Image {
public static let keysIcon = "KeysIcon.icns"
static let disclosureVertiacal = "disclosure-vertical"
static let disclosureHorizontal = "disclosure-horizontal"
}
struct Menu {
/// Sketch's mainMenu.
static let main = NSApplication.shared.mainMenu!
/// A dictionary where keys is titles of Tool Menu Items and the objects is a Sketch action class names associated with it.
static let toolsClassNames = [
"Vector" : "MSInsertVectorAction",
"Pencil" : "MSPencilAction",
"Text" : "MSInsertTextLayerAction",
"Artboard" : "MSInsertArtboardAction",
"Slice" : "MSInsertSliceAction",
// Shape Submenu items
"Line" : "MSInsertLineAction",
"Arrow" : "MSInsertArrowAction",
"Rectangle" : "MSRectangleShapeAction",
"Oval" : "MSOvalShapeAction",
"Rounded" : "MSRoundedRectangleShapeAction",
"Star" : "MSStarShapeAction",
"Polygon" : "MSPolygonShapeAction",
"Triangle": "MSTriangleShapeAction"
]
}
struct MenuItem {
/// An array of manually defined tuples describing a menuItems that shouldn't be customized by Keys.
static let customizableShortcutExceptions: [(title: String, parentItem: String)] = [
// Sketch
// Dynamic system menu. Better to manage through System Preferences
("Services", Const.Menu.main.items[0].title),
// File
// A group of dynamic items
("New from Template", "File"),
// Hidden by Sketch from the main menu
("New from Template…", "File"),
// A group of dynamic items
("Open Recent", "File"),
// A group of dynamic items
("Revert To", "File"),
// A group of dynamic items
("Print", "File"),
// Edit
// Since "Start Dictation" has`fn fn` shortcut by default which we cant easily reassign, skip it too.
("Start Dictation", "Edit"),
// Insert
// Layer
// A group of dynamic items
("Replace With", "Layer")
// Text
// Arrange
// Share
// Plugins
// View
// Window
// Help
]
}
struct Cell {
// OutlineView cells
static let height: CGFloat = 33.0
static let separatorHeight: CGFloat = 8.0
static let dividerHeight: CGFloat = 0.5
}
struct KeyCodeTransformer {
/// A map of non-printed characters Key Codes to its String representations. Values presented in array to match KeyCodeTransformer mapping dictionary data representation.
static let specialKeyCodesMap : [UInt : [String]] = [
UInt(kVK_F1) : [String(unicodeInt: NSF1FunctionKey)],
UInt(kVK_F2) : [String(unicodeInt: NSF2FunctionKey)],
UInt(kVK_F3) : [String(unicodeInt: NSF3FunctionKey)],
UInt(kVK_F4) : [String(unicodeInt: NSF4FunctionKey)],
UInt(kVK_F5) : [String(unicodeInt: NSF5FunctionKey)],
UInt(kVK_F6) : [String(unicodeInt: NSF6FunctionKey)],
UInt(kVK_F7) : [String(unicodeInt: NSF7FunctionKey)],
UInt(kVK_F8) : [String(unicodeInt: NSF8FunctionKey)],
UInt(kVK_F9) : [String(unicodeInt: NSF9FunctionKey)],
UInt(kVK_F10) : [String(unicodeInt: NSF10FunctionKey)],
UInt(kVK_F11) : [String(unicodeInt: NSF11FunctionKey)],
UInt(kVK_F12) : [String(unicodeInt: NSF12FunctionKey)],
UInt(kVK_F13) : [String(unicodeInt: NSF13FunctionKey)],
UInt(kVK_F14) : [String(unicodeInt: NSF14FunctionKey)],
UInt(kVK_F15) : [String(unicodeInt: NSF15FunctionKey)],
UInt(kVK_F16) : [String(unicodeInt: NSF16FunctionKey)],
UInt(kVK_F17) : [String(unicodeInt: NSF17FunctionKey)],
UInt(kVK_F18) : [String(unicodeInt: NSF18FunctionKey)],
UInt(kVK_F19) : [String(unicodeInt: NSF19FunctionKey)],
UInt(kVK_F20) : [String(unicodeInt: NSF20FunctionKey)],
UInt(kVK_Space) : ["\u{20}"],
UInt(kVK_Delete) : [String(unicodeInt: NSBackspaceCharacter)],
UInt(kVK_ForwardDelete) : [String(unicodeInt: NSDeleteCharacter)],
UInt(kVK_ANSI_KeypadClear) : [String(unicodeInt: NSClearLineFunctionKey)],
UInt(kVK_LeftArrow) : [String(unicodeInt: NSLeftArrowFunctionKey), "\u{2190}"],
UInt(kVK_RightArrow) : [String(unicodeInt: NSRightArrowFunctionKey), "\u{2192}"],
UInt(kVK_UpArrow) : [String(unicodeInt: NSUpArrowFunctionKey), "\u{2191}"],
UInt(kVK_DownArrow) : [String(unicodeInt: NSDownArrowFunctionKey), "\u{2193}"],
UInt(kVK_End) : [String(unicodeInt: NSEndFunctionKey)],
UInt(kVK_Home) : [String(unicodeInt: NSHomeFunctionKey)],
UInt(kVK_Escape) : ["\u{1b}"],
UInt(kVK_PageDown) : [String(unicodeInt: NSPageDownFunctionKey)],
UInt(kVK_PageUp) : [String(unicodeInt: NSPageUpFunctionKey)],
UInt(kVK_Return) : [String(unicodeInt: NSCarriageReturnCharacter)],
UInt(kVK_ANSI_KeypadEnter) : [String(unicodeInt: NSEnterCharacter)],
UInt(kVK_Tab) : [String(unicodeInt: NSTabCharacter)],
UInt(kVK_Help) : [String(unicodeInt: NSHelpFunctionKey)],
UInt(kVK_Function) : ["\u{F747}"]
]
}
struct Preferences {
// Identifier used to present Keys in Preferences window.
static let keysIdentifier = NSToolbarItem.Identifier(rawValue: "keysForSketch")
// Keys used to store settings in Preferences
static let kUserKeyEquivalents = "NSUserKeyEquivalents" as CFString
static let kCustomMenuApps = "com.apple.custommenu.apps" as CFString
static let kUniversalAccess = "com.apple.universalaccess" as CFString
}
struct Licensing {
/// Key for local storing of Licensing Info in UserDefaults.
static let kLicensingInfoDefaultsDict = "VDKLicensingInfo"
}
}
fileprivate extension String {
/// Init with unicode int value.
init(unicodeInt: Int) {
self = String(format: "%C", unicodeInt)
}
}
| mit | 4c1719fde379f0438ba5186c2b06f04e | 43.958904 | 178 | 0.603595 | 4.087173 | false | false | false | false |
chenchangqing/learniosRAC | FRP-Swift/FRP-Swift/Models/Enums/ErrorEnum.swift | 1 | 1119 | //
// ErrorEnum.swift
// travelMapMvvm
//
// Created by green on 15/8/29.
// Copyright (c) 2015年 travelMapMvvm. All rights reserved.
//
import Foundation
enum ErrorEnum : String {
case ServerError = "服务器错误"
case JSONError = "JSON转换错误"
case ImageDownloadError = "图片下载失败"
static let allValues = [ServerError,JSONError,ImageDownloadError]
// 位置
var index : Int {
get {
for var i = 0; i < ErrorEnum.allValues.count; i++ {
if self == ErrorEnum.allValues[i] {
return i
}
}
return -1
}
}
// 查询指定位置的元素
static func instance(index:Int) -> ErrorEnum? {
if index >= 0 && index < ErrorEnum.allValues.count {
return ErrorEnum.allValues[index]
}
return nil
}
// errorCode
var errorCode: Int {
get {
return -1000 - index
}
}
} | gpl-2.0 | af633ce4694df5cce1eb40cddbbb856d | 19.113208 | 69 | 0.470423 | 4.650655 | false | false | false | false |
rockbarato/Patience | Patience/Spinner.swift | 1 | 3229 | //
// Spinner.swift
// Patience
//
// Created by Felix Ayala on 10/21/17.
// Copyright © 2017 Pandorga. All rights reserved.
//
import UIKit
open class Spinner: UIView {
open private(set) var isAnimating = false
open let circleLayer = CAShapeLayer()
open var animationDuration: TimeInterval = 2.0
override public init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
open func commonInit() {
self.layer.addSublayer(circleLayer)
circleLayer.fillColor = nil
circleLayer.lineCap = kCALineCapRound
circleLayer.lineWidth = 3.5
circleLayer.strokeColor = UIColor.orange.cgColor
circleLayer.strokeStart = 0
circleLayer.strokeEnd = 0
}
open override func layoutSubviews() {
super.layoutSubviews()
if self.circleLayer.frame != self.bounds {
updateCircleLayer()
}
}
open func updateCircleLayer() {
let center = CGPoint(x: self.bounds.size.width / 2.0, y: self.bounds.size.height / 2.0)
let radius = (self.bounds.height - self.circleLayer.lineWidth) / 2.0
let startAngle: CGFloat = 0.0
let endAngle: CGFloat = 2.0 * CGFloat.pi
let path = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: startAngle,
endAngle: endAngle,
clockwise: true)
self.circleLayer.path = path.cgPath
self.circleLayer.frame = self.bounds
}
open func forceBeginRefreshing() {
self.isAnimating = false
self.beginRefreshing()
}
open func beginRefreshing() {
if self.isAnimating == true {
return
}
self.isAnimating = true
let rotateAnimation = CAKeyframeAnimation(keyPath: "transform.rotation")
rotateAnimation.values = [
0.0,
Float.pi,
(2.0 * Float.pi)
]
let headAnimation = CABasicAnimation(keyPath: "strokeStart")
headAnimation.duration = (self.animationDuration / 2.0)
headAnimation.fromValue = 0
headAnimation.toValue = 0.25
let tailAnimation = CABasicAnimation(keyPath: "strokeEnd")
tailAnimation.duration = (self.animationDuration / 2.0)
tailAnimation.fromValue = 0
tailAnimation.toValue = 1
let endHeadAnimation = CABasicAnimation(keyPath: "strokeStart")
endHeadAnimation.beginTime = (self.animationDuration / 2.0)
endHeadAnimation.duration = (self.animationDuration / 2.0)
endHeadAnimation.fromValue = 0.25
endHeadAnimation.toValue = 1
let endTailAnimation = CABasicAnimation(keyPath: "strokeEnd")
endTailAnimation.beginTime = (self.animationDuration / 2.0)
endTailAnimation.duration = (self.animationDuration / 2.0)
endTailAnimation.fromValue = 1
endTailAnimation.toValue = 1
let animations = CAAnimationGroup()
animations.duration = self.animationDuration
animations.animations = [
rotateAnimation,
headAnimation,
tailAnimation,
endHeadAnimation,
endTailAnimation
]
animations.repeatCount = Float.infinity
animations.isRemovedOnCompletion = false
self.circleLayer.add(animations, forKey: "animations")
}
open func endRefreshing () {
self.isAnimating = false
self.circleLayer.removeAnimation(forKey: "animations")
}
}
| mit | b18b9188737c43c29ce0cc59d2dda554 | 24.619048 | 89 | 0.703222 | 3.829181 | false | false | false | false |
bitboylabs/selluv-ios | selluv-ios/selluv-ios/Classes/Base/Vender/Atomic/Lock.swift | 2 | 1128 | //
// Lock.swift
// Atomic
//
// Created by Adlai Holler on 1/31/16.
// Copyright © 2016 Adlai Holler. All rights reserved.
//
import Darwin
final public class Lock {
internal var _lock = pthread_mutex_t()
/// Initializes the variable with the given initial value.
public init() {
let result = pthread_mutex_init(&_lock, nil)
assert(result == 0, "Failed to init mutex in \(self)")
}
public func lock() {
let result = pthread_mutex_lock(&_lock)
assert(result == 0, "Failed to lock mutex in \(self)")
}
public func tryLock() -> Int32 {
return pthread_mutex_trylock(&_lock)
}
public func unlock() {
let result = pthread_mutex_unlock(&_lock)
assert(result == 0, "Failed to unlock mutex in \(self)")
}
deinit {
let result = pthread_mutex_destroy(&_lock)
assert(result == 0, "Failed to destroy mutex in \(self)")
}
}
extension Lock {
public func withCriticalScope<Result>(body: () throws -> Result) rethrows -> Result {
lock()
defer { unlock() }
return try body()
}
}
| mit | db61c5d77b1bedfac3351be2644a9b62 | 22.978723 | 89 | 0.588287 | 3.926829 | false | false | false | false |
AjayOdedara/CoreKitTest | CoreKit/CoreKit/Locksmith.swift | 1 | 11912 | //
// Locksmith.swift
//
// Created by CllearWorks Dev on 26/10/2014.
// Copyright (c) 2014 Colour Coding. All rights reserved.
//
import Foundation
import Security
public let LocksmithErrorDomain = "com.locksmith.error"
public let LocksmithDefaultService = "com.locksmith.defaultService"
@objc public class Locksmith: NSObject {
// MARK: Perform request
public class func performRequest(request: LocksmithRequest) -> (NSDictionary?, NSError?) {
let type = request.type
//var result: Unmanaged<AnyObject>? = nil
var result: AnyObject?
var status: OSStatus?
let parsedRequest: NSMutableDictionary = parseRequest(request: request)
let requestReference = parsedRequest as CFDictionary
switch type {
case .Create:
status = withUnsafeMutablePointer(to: &result) { SecItemAdd(requestReference, UnsafeMutablePointer($0)) }
case .Read:
status = withUnsafeMutablePointer(to: &result) { SecItemCopyMatching(requestReference, UnsafeMutablePointer($0)) }
case .Delete:
status = SecItemDelete(requestReference)
case .Update:
status = Locksmith.performUpdate(request: requestReference, result: &result)
}
if let status = status {
let statusCode = Int(status)
let error = Locksmith.keychainError(forCode: statusCode)
var resultsDictionary: NSDictionary?
if result != nil {
if type == .Read && status == errSecSuccess {
if let data = result as? NSData {
// Convert the retrieved data to a dictionary
resultsDictionary = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? NSDictionary
}
}
}
return (resultsDictionary, error)
} else {
let code = LocksmithErrorCode.TypeNotFound.rawValue
let message = internalErrorMessage(forCode: code)
return (nil, NSError(domain: LocksmithErrorDomain, code: code, userInfo: ["message": message]))
}
}
private class func performUpdate(request: CFDictionary, result: inout AnyObject?) -> OSStatus {
// We perform updates to the keychain by first deleting the matching object, then writing to it with the new value.
SecItemDelete(request)
// Even if the delete request failed (e.g. if the item didn't exist before), still try to save the new item.
// If we get an error saving, we'll tell the user about it.
let status: OSStatus = withUnsafeMutablePointer(to: &result) { SecItemAdd(request, UnsafeMutablePointer($0)) }
return status
}
// MARK: Error Lookup
enum ErrorMessage: String {
case Allocate = "Failed to allocate memory."
case AuthFailed = "Authorization/Authentication failed."
case Decode = "Unable to decode the provided data."
case Duplicate = "The item already exists."
case InteractionNotAllowed = "Interaction with the Security Server is not allowed."
case NoError = "No error."
case NotAvailable = "No trust results are available."
case NotFound = "The item cannot be found."
case Param = "One or more parameters passed to the function were not valid."
case Unimplemented = "Function or operation not implemented."
}
enum LocksmithErrorCode: Int {
case RequestNotSet = 1
case TypeNotFound = 2
case UnableToClear = 3
}
enum LocksmithErrorMessage: String {
case RequestNotSet = "keychainRequest was not set."
case TypeNotFound = "The type of request given was undefined."
case UnableToClear = "Unable to clear the keychain"
}
class func keychainError(forCode statusCode: Int) -> NSError? {
var error: NSError?
if statusCode != Int(errSecSuccess) {
let message = errorMessage(code: statusCode)
// print("Keychain request failed. Code: \(statusCode). Message: \(message)")
error = NSError(domain: LocksmithErrorDomain, code: statusCode, userInfo: ["message": message])
}
return error
}
// MARK: Private methods
public class func internalErrorMessage(forCode statusCode: Int) -> NSString {
switch statusCode {
case LocksmithErrorCode.RequestNotSet.rawValue:
return LocksmithErrorMessage.RequestNotSet.rawValue as NSString
case LocksmithErrorCode.UnableToClear.rawValue:
return LocksmithErrorMessage.UnableToClear.rawValue as NSString
default:
return "Error message for code \(statusCode) not set" as NSString
}
}
private class func parseRequest(request: LocksmithRequest) -> NSMutableDictionary {
var parsedRequest = NSMutableDictionary()
var options = [String: AnyObject?]()
options[String(kSecAttrAccount)] = request.userAccount as AnyObject
options[String(kSecAttrAccessGroup)] = request.group as AnyObject
options[String(kSecAttrService)] = request.service as AnyObject
options[String(kSecAttrSynchronizable)] = request.synchronizable as AnyObject
options[String(kSecClass)] = securityCode(securityClass: request.securityClass)
if let accessibleMode = request.accessible {
options[String(kSecAttrAccessible)] = accessible(accessible: accessibleMode)
}
for (key, option) in options {
parsedRequest.setOptional(optional: option, forKey: key as NSCopying)
}
switch request.type {
case .Create:
parsedRequest = parseCreateRequest(request: request, inDictionary: parsedRequest)
case .Delete:
parsedRequest = parseDeleteRequest(request: request, inDictionary: parsedRequest)
case .Update:
parsedRequest = parseCreateRequest(request: request, inDictionary: parsedRequest)
default: // case .Read:
parsedRequest = parseReadRequest(request: request, inDictionary: parsedRequest)
}
return parsedRequest
}
private class func parseCreateRequest(request: LocksmithRequest, inDictionary dictionary: NSMutableDictionary) -> NSMutableDictionary {
if let data = request.data {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: data)
dictionary.setObject(encodedData, forKey: kSecValueData as! NSCopying)//dictionary.setObject(encodedData, forKey: String(kSecValueData))
}
return dictionary
}
private class func parseReadRequest(request: LocksmithRequest, inDictionary dictionary: NSMutableDictionary) -> NSMutableDictionary {
dictionary.setOptional(optional: kCFBooleanTrue, forKey: kSecReturnData as! NSCopying)
switch request.matchLimit {
case .One:
dictionary.setObject(kSecMatchLimitOne, forKey: kSecMatchLimit as! NSCopying)
case .Many:
dictionary.setObject(kSecMatchLimitAll, forKey: kSecMatchLimit as! NSCopying)//String(kSecMatchLimit))
}
return dictionary
}
private class func parseDeleteRequest(request: LocksmithRequest, inDictionary dictionary: NSMutableDictionary) -> NSMutableDictionary {
return dictionary
}
private class func errorMessage(code: Int) -> NSString {
switch code {
case Int(errSecAllocate):
return ErrorMessage.Allocate.rawValue as NSString
case Int(errSecAuthFailed):
return ErrorMessage.AuthFailed.rawValue as NSString
case Int(errSecDecode):
return ErrorMessage.Decode.rawValue as NSString
case Int(errSecDuplicateItem):
return ErrorMessage.Duplicate.rawValue as NSString
case Int(errSecInteractionNotAllowed):
return ErrorMessage.InteractionNotAllowed.rawValue as NSString
case Int(errSecItemNotFound):
return ErrorMessage.NotFound.rawValue as NSString
case Int(errSecNotAvailable):
return ErrorMessage.NotAvailable.rawValue as NSString
case Int(errSecParam):
return ErrorMessage.Param.rawValue as NSString
case Int(errSecSuccess):
return ErrorMessage.NoError.rawValue as NSString
case Int(errSecUnimplemented):
return ErrorMessage.Unimplemented.rawValue as NSString
default:
return "Undocumented error with code \(code)." as NSString
}
}
private class func securityCode(securityClass: SecurityClass) -> CFString {
switch securityClass {
case .GenericPassword:
return kSecClassGenericPassword
case .Certificate:
return kSecClassCertificate
case .Identity:
return kSecClassIdentity
case .InternetPassword:
return kSecClassInternetPassword
case .Key:
return kSecClassKey
}
}
private class func accessible(accessible: Accessible) -> CFString{//Ref {
switch accessible {
case .WhenUnlock:
return kSecAttrAccessibleWhenUnlocked
case .AfterFirstUnlock:
return kSecAttrAccessibleAfterFirstUnlock
case .Always:
return kSecAttrAccessibleAlways
case .WhenPasscodeSetThisDeviceOnly:
return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
case .WhenUnlockedThisDeviceOnly:
return kSecAttrAccessibleWhenUnlockedThisDeviceOnly
case .AfterFirstUnlockThisDeviceOnly:
return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
case .AlwaysThisDeviceOnly:
return kSecAttrAccessibleAlwaysThisDeviceOnly
}
}
}
// MARK: Convenient Class Methods
extension Locksmith {
public class func saveData(data: Dictionary<String, String>, forUserAccount userAccount: String, inService service: String = LocksmithDefaultService) -> NSError? {
let saveRequest = LocksmithRequest(userAccount: userAccount, requestType: .Create, data: data as NSDictionary, service: service)
let (_, error) = Locksmith.performRequest(request: saveRequest)
return error
}
public class func loadDataForUserAccount(userAccount: String, inService service: String = LocksmithDefaultService) -> (NSDictionary?, NSError?) {
let readRequest = LocksmithRequest(userAccount: userAccount, service: service)
return Locksmith.performRequest(request: readRequest)
}
public class func deleteDataForUserAccount(userAccount: String, inService service: String = LocksmithDefaultService) -> NSError? {
let deleteRequest = LocksmithRequest(userAccount: userAccount, requestType: .Delete, service: service)
let (_, error) = Locksmith.performRequest(request: deleteRequest)
return error
}
public class func updateData(data: Dictionary<String, String>, forUserAccount userAccount: String, inService service: String = LocksmithDefaultService) -> NSError? {
let updateRequest = LocksmithRequest(userAccount: userAccount, requestType: .Update, data: data as NSDictionary, service: service)
let (_, error) = Locksmith.performRequest(request: updateRequest)
return error
}
public class func clearKeychain() -> NSError? {
// Delete all of the keychain data of the given class
func deleteDataForSecClass(secClass: CFTypeRef) -> NSError? {
let request = NSMutableDictionary()
request.setObject(secClass, forKey: kSecClass as! NSCopying)//String(kSecClass))
let status: OSStatus? = SecItemDelete(request as CFDictionary)
if let status = status {
let statusCode = Int(status)
return Locksmith.keychainError(forCode: statusCode)
}
return nil
}
// For each of the sec class types, delete all of the saved items of that type
let classes = [kSecClassGenericPassword, kSecClassInternetPassword, kSecClassCertificate, kSecClassKey, kSecClassIdentity]
let errors: [NSError?] = classes.map({
return deleteDataForSecClass(secClass: $0)
})
// Remove those that were successful, or failed with an acceptable error code
let filtered = errors.filter({
if let error = $0 {
// There was an error
// If the error indicates that there was no item with that sec class, that's fine.
// Some of the sec classes will have nothing in them in most cases.
return error.code != Int(errSecItemNotFound) ? true : false
}
// There was no error
return false
})
// If the filtered array is empty, then everything went OK
if filtered.isEmpty {
return nil
}
// At least one of the delete operations failed
let code = LocksmithErrorCode.UnableToClear.rawValue
let message = internalErrorMessage(forCode: code)//internaler//internalErrorMessage(forCode: code)
return NSError(domain: LocksmithErrorDomain, code: code, userInfo: ["message": message])
}
}
// MARK: Dictionary Extensions
extension NSMutableDictionary {
func setOptional(optional: AnyObject?, forKey key: NSCopying) {
if let object: AnyObject = optional {
self.setObject(object, forKey: key)
}
}
}
| mit | 064733b51576ffc4295410e5a5fcd6b5 | 35.879257 | 166 | 0.756212 | 4.406955 | false | false | false | false |
ello/ello-ios | Sources/Model/Regions/EmbedRegion.swift | 1 | 2804 | ////
/// EmbedRegion.swift
//
import SwiftyJSON
let EmbedRegionVersion = 1
@objc(EmbedRegion)
final class EmbedRegion: Model, Regionable {
enum Service: String {
case codepen = "codepen"
case dailymotion = "dailymotion"
case mixcloud = "mixcloud"
case soundcloud = "soundcloud"
case youtube = "youtube"
case vimeo = "vimeo"
case uStream = "ustream"
case bandcamp = "bandcamp"
case unknown = "unknown"
}
let id: String
let service: Service
let url: URL
let thumbnailLargeUrl: URL?
var isRepost: Bool = false
let kind: RegionKind = .embed
var isAudioEmbed: Bool {
return service == Service.mixcloud || service == Service.soundcloud
|| service == Service.bandcamp
}
init(
id: String,
service: Service,
url: URL,
thumbnailLargeUrl: URL?
) {
self.id = id
self.service = service
self.url = url
self.thumbnailLargeUrl = thumbnailLargeUrl
super.init(version: EmbedRegionVersion)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
self.id = decoder.decodeKey("id")
self.isRepost = decoder.decodeKey("isRepost")
let serviceRaw: String = decoder.decodeKey("serviceRaw")
self.service = Service(rawValue: serviceRaw) ?? Service.unknown
self.url = decoder.decodeKey("url")
self.thumbnailLargeUrl = decoder.decodeOptionalKey("thumbnailLargeUrl")
super.init(coder: coder)
}
override func encode(with encoder: NSCoder) {
let coder = Coder(encoder)
coder.encodeObject(id, forKey: "id")
coder.encodeObject(isRepost, forKey: "isRepost")
coder.encodeObject(service.rawValue, forKey: "serviceRaw")
coder.encodeObject(url, forKey: "url")
coder.encodeObject(thumbnailLargeUrl, forKey: "thumbnailLargeUrl")
super.encode(with: coder.coder)
}
class func fromJSON(_ data: [String: Any]) -> EmbedRegion {
let json = JSON(data)
let thumbnailLargeUrl = json["data"]["thumbnail_large_url"].url
let embedRegion = EmbedRegion(
id: json["data"]["id"].stringValue,
service: Service(rawValue: json["data"]["service"].stringValue) ?? .unknown,
url: URL(string: json["data"]["url"].stringValue) ?? URL(
string: "https://ello.co/404"
)!,
thumbnailLargeUrl: thumbnailLargeUrl
)
return embedRegion
}
func coding() -> NSCoding {
return self
}
func toJSON() -> [String: Any] {
return [
"kind": kind.rawValue,
"data": [
"url": url.absoluteString,
],
]
}
}
| mit | ac05de67b70cddf0f296228ceb413b2a | 27.612245 | 88 | 0.587732 | 4.242057 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/Foundation/URLSession+Rx.swift | 13 | 8589 | //
// URLSession+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 3/23/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import struct Foundation.URL
import struct Foundation.URLRequest
import struct Foundation.Data
import struct Foundation.Date
import struct Foundation.TimeInterval
import class Foundation.HTTPURLResponse
import class Foundation.URLSession
import class Foundation.URLResponse
import class Foundation.JSONSerialization
import class Foundation.NSError
import var Foundation.NSURLErrorCancelled
import var Foundation.NSURLErrorDomain
#if os(Linux)
// don't know why
import Foundation
#endif
import RxSwift
/// RxCocoa URL errors.
public enum RxCocoaURLError
: Swift.Error {
/// Unknown error occurred.
case unknown
/// Response is not NSHTTPURLResponse
case nonHTTPResponse(response: URLResponse)
/// Response is not successful. (not in `200 ..< 300` range)
case httpRequestFailed(response: HTTPURLResponse, data: Data?)
/// Deserialization error.
case deserializationError(error: Swift.Error)
}
extension RxCocoaURLError
: CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error has occurred."
case let .nonHTTPResponse(response):
return "Response is not NSHTTPURLResponse `\(response)`."
case let .httpRequestFailed(response, _):
return "HTTP request failed with `\(response.statusCode)`."
case let .deserializationError(error):
return "Error during deserialization of the response: \(error)"
}
}
}
private func escapeTerminalString(_ value: String) -> String {
return value.replacingOccurrences(of: "\"", with: "\\\"", options:[], range: nil)
}
fileprivate func convertURLRequestToCurlCommand(_ request: URLRequest) -> String {
let method = request.httpMethod ?? "GET"
var returnValue = "curl -X \(method) "
if let httpBody = request.httpBody, request.httpMethod == "POST" {
let maybeBody = String(data: httpBody, encoding: String.Encoding.utf8)
if let body = maybeBody {
returnValue += "-d \"\(escapeTerminalString(body))\" "
}
}
for (key, value) in request.allHTTPHeaderFields ?? [:] {
let escapedKey = escapeTerminalString(key as String)
let escapedValue = escapeTerminalString(value as String)
returnValue += "\n -H \"\(escapedKey): \(escapedValue)\" "
}
let URLString = request.url?.absoluteString ?? "<unknown url>"
returnValue += "\n\"\(escapeTerminalString(URLString))\""
returnValue += " -i -v"
return returnValue
}
private func convertResponseToString(_ response: URLResponse?, _ error: NSError?, _ interval: TimeInterval) -> String {
let ms = Int(interval * 1000)
if let response = response as? HTTPURLResponse {
if 200 ..< 300 ~= response.statusCode {
return "Success (\(ms)ms): Status \(response.statusCode)"
}
else {
return "Failure (\(ms)ms): Status \(response.statusCode)"
}
}
if let error = error {
if error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled {
return "Canceled (\(ms)ms)"
}
return "Failure (\(ms)ms): NSError > \(error)"
}
return "<Unhandled response from server>"
}
extension Reactive where Base: URLSession {
/**
Observable sequence of responses for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
- parameter request: URL request.
- returns: Observable sequence of URL responses.
*/
public func response(request: URLRequest) -> Observable<(response: HTTPURLResponse, data: Data)> {
return Observable.create { observer in
// smart compiler should be able to optimize this out
let d: Date?
if Logging.URLRequests(request) {
d = Date()
}
else {
d = nil
}
let task = self.base.dataTask(with: request) { data, response, error in
if Logging.URLRequests(request) {
let interval = Date().timeIntervalSince(d ?? Date())
print(convertURLRequestToCurlCommand(request))
#if os(Linux)
print(convertResponseToString(response, error.flatMap { $0 as NSError }, interval))
#else
print(convertResponseToString(response, error.map { $0 as NSError }, interval))
#endif
}
guard let response = response, let data = data else {
observer.on(.error(error ?? RxCocoaURLError.unknown))
return
}
guard let httpResponse = response as? HTTPURLResponse else {
observer.on(.error(RxCocoaURLError.nonHTTPResponse(response: response)))
return
}
observer.on(.next((httpResponse, data)))
observer.on(.completed)
}
task.resume()
return Disposables.create(with: task.cancel)
}
}
/**
Observable sequence of response data for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
- parameter request: URL request.
- returns: Observable sequence of response data.
*/
public func data(request: URLRequest) -> Observable<Data> {
return self.response(request: request).map { pair -> Data in
if 200 ..< 300 ~= pair.0.statusCode {
return pair.1
}
else {
throw RxCocoaURLError.httpRequestFailed(response: pair.0, data: pair.1)
}
}
}
/**
Observable sequence of response JSON for URL request.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter request: URL request.
- returns: Observable sequence of response JSON.
*/
public func json(request: URLRequest, options: JSONSerialization.ReadingOptions = []) -> Observable<Any> {
return self.data(request: request).map { data -> Any in
do {
return try JSONSerialization.jsonObject(with: data, options: options)
} catch let error {
throw RxCocoaURLError.deserializationError(error: error)
}
}
}
/**
Observable sequence of response JSON for GET request with `URL`.
Performing of request starts after observer is subscribed and not after invoking this method.
**URL requests will be performed per subscribed observer.**
Any error during fetching of the response will cause observed sequence to terminate with error.
If response is not HTTP response with status code in the range of `200 ..< 300`, sequence
will terminate with `(RxCocoaErrorDomain, RxCocoaError.NetworkError)`.
If there is an error during JSON deserialization observable sequence will fail with that error.
- parameter url: URL of `NSURLRequest` request.
- returns: Observable sequence of response JSON.
*/
public func json(url: Foundation.URL) -> Observable<Any> {
return self.json(request: URLRequest(url: url))
}
}
| mit | 766d225551d8a4ebe08b4cdd3830a627 | 34.341564 | 119 | 0.639264 | 5.278427 | false | false | false | false |
bull-xu-stride/MaterialDesignIcons.Swift | MaterialDesignIconsSwift/MaterialDesignIcons.swift | 1 | 7924 | //
// MaterialDesignIcons.swift
// MaterialDesignIconsSwift
//
// Created by Bull Xu on 8/09/2016.
// Copyright © 2016 Stride Solutions. All rights reserved.
//
import Foundation
import UIKit
/**
A MaterialDesignIcons extension to UIFont.
*/
public extension UIFont {
/**
Gets a UIFont object of MaterialDesignIcons.
- parameter fontSize: The preferred font size.
- returns: A UIFont object of MaterialDesignIcons.
*/
public class func fontMaterialDesignIcons(ofSize fontSize: CGFloat) -> UIFont? {
return MaterialDesignIcons.font(ofSize: fontSize)
}
}
/**
A protocol to provide font's file name, extension and font name.
This protocol can be used to any icon fonts, such as FontAwsome etc.
*/
public protocol FontIconProcotol {
/** Font file name in the bundle. */
static var fontFilename: String { get }
/** Font file extension name, e.g. ttf. */
static var fontFileExtension: String { get }
/**
Font name. Use Font Book app to install the font, select "Show Font Info"
from "View" menu, the value of "PostScript name" is the font name to be used in Xcode.
*/
static var fontName: String { get }
static var familyName: String { get }
/** RawValue of the Enum type. */
var rawValue: String { get }
}
extension FontIconProcotol {
/**
Gets a UIFont object by the provided font information of this protocol.
- parameter fontSize: The preferred font size.
- returns: A UIFont object.
*/
public static func font(ofSize fontSize: CGFloat) -> UIFont? {
if UIFont.fontNames(forFamilyName: familyName).isEmpty {
FontLoader.loadFont(fontFilename, withExtension: fontFileExtension)
}
return UIFont(name: fontName, size: fontSize)
}
/**
Returns the string value of the font Enum value's rawValue.
*/
public var stringValue: String {
let index = rawValue.index(rawValue.startIndex, offsetBy: 1)
return String(rawValue[..<index])
}
/**
Converts the font icon to an attributed string.
- parameter textColor: The preferred foreground color, default is `UIColor.white`
- parameter fontSize: The preferred font size, default is 24.
- parameter backgroundColor: The preferred background color, default is `UIColor.clear`
- parameter alignment: The preferred alignment, default is `NSTextAlignment.center`
*/
public func attributedString(
_ textColor: UIColor = .white,
fontSize: CGFloat = 24,
backgroundColor: UIColor = .clear,
alignment: NSTextAlignment = .center) -> NSAttributedString {
guard let font = Self.font(ofSize: fontSize) else {
return NSAttributedString()
}
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = alignment
let attrs: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: textColor,
.backgroundColor: backgroundColor,
.paragraphStyle: paragraph
]
let attributedString = NSAttributedString(string: stringValue, attributes: attrs)
return attributedString
}
/**
Converts the font icon to an image.
- parameter textColor: The preferred foreground color, default is `UIColor.white`
- parameter size: The preferred image size, default is (24, 24).
If the width and height is not equal, use the min value.
- parameter backgroundColor: The preferred background color, default is `UIColor.clear`
- parameter fontAspectRatio: The font aspect ratio, defaut is 1 (without scaling).
*/
public func image(
_ textColor: UIColor = .white,
size: CGSize = CGSize(width: 24, height: 24),
backgroundColor: UIColor = .clear,
fontAspectRatio: CGFloat = 1) -> UIImage {
assert(fontAspectRatio > 0.0)
let fontSize = max(1, min(size.width / fontAspectRatio, size.height))
let attributedString = self.attributedString(
textColor,
fontSize: fontSize,
backgroundColor: backgroundColor)
UIGraphicsBeginImageContextWithOptions(size, false , 0.0)
let rect = CGRect(x: 0, y: (size.height - fontSize) / 2, width: size.width, height: fontSize)
attributedString.draw(in: rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image ?? UIImage()
}
}
/**
Implements the FontIconProcotol to the icon enums.
*/
extension MaterialDesignIcons: FontIconProcotol {
public static var fontFilename: String {
return "materialdesignicons-webfont"
}
public static var fontFileExtension: String {
return "ttf"
}
public static var fontName: String {
return "Material-Design-Icons"
}
public static var familyName: String {
return "Material Design Icons"
}
}
extension UIImage {
/**
Initializes and returns an image object with the specified icon and properties.
- parameter textColor: The preferred foreground color, default is `UIColor.white`
- parameter size: The preferred image size, default is (24, 24).
If the width and height is not equal, use the min value.
- parameter backgroundColor: The preferred background color, default is `UIColor.clear`
- parameter fontAspectRatio: The font aspect ratio, defaut is 1 (without scaling).
*/
public convenience init?(
icon: FontIconProcotol,
color: UIColor = .white,
size: CGSize = CGSize(width: 24, height: 24),
backgroundColor: UIColor = .clear,
fontAspectRatio: CGFloat = 1) {
let img = icon.image(
color,
size: size,
backgroundColor: backgroundColor,
fontAspectRatio: fontAspectRatio)
guard let cgImage = img.cgImage else {
return nil
}
self.init(cgImage: cgImage, scale: img.scale, orientation: img.imageOrientation)
}
}
extension NSAttributedString {
/**
Returns an `NSAttributedString` object initialized with the specified icon and properties.
- parameter textColor: The preferred foreground color, default is `UIColor.white`
- parameter size: The preferred image size, default is (24, 24).
If the width and height is not equal, use the min value.
- parameter backgroundColor: The preferred background color, default is `UIColor.clear`
- parameter fontAspectRatio: The font aspect ratio, defaut is 1 (without scaling).
*/
public convenience init(
icon: FontIconProcotol,
textColor: UIColor = UIColor.white,
fontSize: CGFloat = 24,
backgroundColor: UIColor = UIColor.clear,
alignment: NSTextAlignment = .center) {
let attr = icon.attributedString(
textColor,
fontSize: fontSize,
backgroundColor: backgroundColor,
alignment: alignment)
self.init(attributedString: attr)
}
}
extension UIImageView {
/**
Initializes and returns a newly allocated view object with the specified
frame rectangle and font icon value.
- parameter frame: The frame rectangle for the view, measured in points.
- parameter fontIcon: The font icon value.
*/
public convenience init(frame: CGRect, fontIcon: FontIconProcotol) {
self.init(frame: frame)
setImage(fontIcon)
}
/**
Set the image by specified font icon, with the image view's tintColor,
frame's size and backgroundColor.
- parameter fontIcon: The font icon value.
*/
public func setImage(_ fontIcon: FontIconProcotol) {
image = fontIcon.image(
tintColor ?? .black,
size: frame.size,
backgroundColor: backgroundColor ?? .clear)
}
}
extension UILabel {
/**
Initializes and returns a newly allocated view object with the specified
frame rectangle and font icon value.
- parameter frame: The frame rectangle for the view, measured in points.
- parameter fontIcon: The font icon value.
*/
public convenience init(frame: CGRect, fontIcon: FontIconProcotol) {
self.init(frame: frame)
setAttributedText(fontIcon)
}
/**
Sets the attributed text by specified font icon, with the label's tintColor,
frame's size and backgroundColor.
- parameter fontIcon: The font icon value.
*/
public func setAttributedText(_ fontIcon: FontIconProcotol) {
attributedText = fontIcon.attributedString(
tintColor ?? .black,
fontSize: font.pointSize,
backgroundColor: backgroundColor ?? .clear)
}
}
| mit | 0b1da4d8c48b4367321a8c5dd0b2dd6a | 27.810909 | 95 | 0.729143 | 3.941791 | false | false | false | false |
RobotPajamas/SwiftyTeeth | SwiftyTeeth Sample/UI/PeripheralView.swift | 1 | 4269 | //
// DeviceView.swift
// SwiftyTeeth Sample
//
// Created by SJ on 2020-03-27.
//
import SwiftyTeeth
import SwiftUI
final class PeripheralViewModel: ObservableObject {
let peripheral: Device
let serviceUuid = UUID(uuidString: "00726f62-6f74-7061-6a61-6d61732e6361")!
let txUuid = UUID(uuidString: "01726f62-6f74-7061-6a61-6d61732e6361")!
let rxUuid = UUID(uuidString: "02726f62-6f74-7061-6a61-6d61732e6361")!
@Published var logMessage = ""
init(peripheral: Device) {
self.peripheral = peripheral
peripheral.connectionStateChangedHandler = { state in
self.log("Connection state is \(state)")
}
}
private func log(_ text: String) {
print(text)
DispatchQueue.main.async {
self.logMessage.append(text + "\n")
}
}
func connect() {
peripheral.connect { (connectionState) in
guard connectionState == .connected else {
self.log("Not connected")
return
}
self.log("App: Device is connected? \(connectionState == .connected)")
self.log("App: Starting service discovery...")
self.peripheral.discoverServices { (result) in
let services = (try? result.get()) ?? []
services.forEach { (service) in
self.log("App: Discovering characteristics for service: \(service.uuid.uuidString)")
self.peripheral.discoverCharacteristics(for: service) { (result) in
let characteristics = (try? result.get().characteristics) ?? []
characteristics.forEach { (characteristuc) in
self.log("App: Discovered characteristic: \(characteristuc.uuid.uuidString) in \(String(describing: service.uuid.uuidString))")
}
if service.uuid == services.last?.uuid {
self.log("App: All services/characteristics discovered")
}
}
}
}
}
}
func disconnect() {
peripheral.disconnect()
}
func subscribe() {
peripheral.subscribe(to: rxUuid, in: serviceUuid) { result in
switch result {
case .success(let value):
self.log("Subscribed value: \([UInt8](value))")
case .failure(let error):
self.log("Subscribed value returned nil \(error)")
}
}
}
func read() {
peripheral.read(from: rxUuid, in: serviceUuid) { (result) in
switch result {
case .success(let value):
self.log("Read value: \([UInt8](value))")
case .failure(let error):
self.log("Read returned nil \(error)")
}
}
}
func write() {
let command = Data([0x01])
peripheral.write(data: command, to: txUuid, in: serviceUuid) { result in
switch result {
case .success:
self.log("Write with response was successful")
case .failure(let error):
self.log("Write with response was unsuccessful \(error)")
}
}
}
}
struct PeripheralView: View {
@ObservedObject var vm: PeripheralViewModel
let peripheral: Device
init(peripheral: Device) {
self.peripheral = peripheral
self.vm = PeripheralViewModel(peripheral: peripheral)
}
var body: some View {
VStack {
HStack {
Spacer()
Button("Subscribe") {
self.vm.subscribe()
}
Spacer()
Button("Read") {
self.vm.read()
}
Spacer()
Button("Write") {
self.vm.write()
}
Spacer()
}
TextView(text: $vm.logMessage, autoscroll: true)
}.onAppear {
self.vm.connect()
}.onDisappear {
self.vm.disconnect()
}.navigationBarTitle("Peripheral", displayMode: .inline)
}
}
| apache-2.0 | 46ec1347b440b245be9d117364f0716c | 30.858209 | 155 | 0.513469 | 4.802025 | false | false | false | false |
austinzheng/swift | test/IRGen/reflection_metadata_let_var.swift | 36 | 753 | // RUN: %target-swift-frontend -emit-ir %s | %FileCheck %s
// CHECK: [[INT:@.*]] = linkonce_odr hidden constant {{.*}} c"Si"
// CHECK: [[X:@.*]] = private constant {{.*}} c"x\00"
// CHECK: [[STRING:@.*]] = linkonce_odr hidden constant {{.*}} c"SS"
// CHECK: [[Y:@.*]] = private constant {{.*}} c"y\00"
// CHECK-LABEL: @"$s27reflection_metadata_let_var6StruccVMF" = internal constant
struct Strucc {
// -- flags (let)
// CHECK-SAME: i32 0,
// -- type
// CHECK-SAME: [[INT]] to
// -- name
// CHECK-SAME: [[X]] to
let x: Int
// -- flags (var)
// CHECK-SAME: i32 2,
// -- type
// CHECK-SAME: [[STRING]] to
// -- name
// CHECK-SAME: [[Y]] to
var y: String
}
| apache-2.0 | 53415140ddbb78c0e64f19349dd903b8 | 27.961538 | 80 | 0.49004 | 3.1375 | false | false | false | false |
austinzheng/swift | validation-test/compiler_crashers_fixed/01702-swift-type-walk.swift | 65 | 1136 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
}
protocol c {
class a<T> Int = B)
func e> String {
S()-> {
class d<d
func f, range.Type) ->(T, 3)
class a {
c<f == {
}
typealias B == f<f = c({
class A : Any, b = B<T> T, d, e == compose<T>Bool))) -> Self {
typealias h: T>((")
var e: A, y)
static let foo as a(A, (self.dynamicType)
func e({
}
func a(h> () {
}
struct S {
class c()
}
protocol b {
import Foundation
}
}
}
}
}
extension NSSet {
print())
protocol b {
}
}
var b[()
}
(""
return g, k : T, () -> e? = 1, x = i().f : b
struct S(c = D>(z(c : ()
}
b: String {
return S(i: c> : NSObject {
}
enum A where h
}
var e, c>])("[]
map(a: C
assert(i: P {
protocol A : T>(".B
typealias e : B(t: Sequence, f<T>, e)
f() -> Int = f, i(")
enum B : c(f(c(x(""")
enum A = [Byte])
func g<C: B.a:
| apache-2.0 | 0809e8f95b302ee7dabd0d4bc3b16708 | 17.322581 | 79 | 0.600352 | 2.617512 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/SmallString.swift | 2 | 13929 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// The code units in _SmallString are always stored in memory in the same order
// that they would be stored in an array. This means that on big-endian
// platforms the order of the bytes in storage is reversed compared to
// _StringObject whereas on little-endian platforms the order is the same.
//
// Memory layout:
//
// |0 1 2 3 4 5 6 7 8 9 A B C D E F| ← hexadecimal offset in bytes
// | _storage.0 | _storage.1 | ← raw bits
// | code units | | ← encoded layout
// ↑ ↑
// first (leftmost) code unit discriminator (incl. count)
//
// On Android AArch64, there is one less byte available because the discriminator
// is stored in the penultimate code unit instead, to match where it's stored
// for large strings.
@frozen @usableFromInline
internal struct _SmallString {
@usableFromInline
internal typealias RawBitPattern = (UInt64, UInt64)
// Small strings are values; store them raw
@usableFromInline
internal var _storage: RawBitPattern
@inlinable @inline(__always)
internal var rawBits: RawBitPattern { return _storage }
@inlinable
internal var leadingRawBits: UInt64 {
@inline(__always) get { return _storage.0 }
@inline(__always) set { _storage.0 = newValue }
}
@inlinable
internal var trailingRawBits: UInt64 {
@inline(__always) get { return _storage.1 }
@inline(__always) set { _storage.1 = newValue }
}
@inlinable @inline(__always)
internal init(rawUnchecked bits: RawBitPattern) {
self._storage = bits
}
@inlinable @inline(__always)
internal init(raw bits: RawBitPattern) {
self.init(rawUnchecked: bits)
_invariantCheck()
}
@inlinable @inline(__always)
internal init(_ object: _StringObject) {
_internalInvariant(object.isSmall)
// On big-endian platforms the byte order is the reverse of _StringObject.
let leading = object.rawBits.0.littleEndian
let trailing = object.rawBits.1.littleEndian
self.init(raw: (leading, trailing))
}
@inlinable @inline(__always)
internal init() {
self.init(_StringObject(empty:()))
}
}
extension _SmallString {
@inlinable @inline(__always)
internal static var capacity: Int {
#if arch(i386) || arch(arm) || arch(arm64_32) || arch(wasm32)
return 10
#elseif os(Android) && arch(arm64)
return 14
#else
return 15
#endif
}
// Get an integer equivalent to the _StringObject.discriminatedObjectRawBits
// computed property.
@inlinable @inline(__always)
internal var rawDiscriminatedObject: UInt64 {
// Reverse the bytes on big-endian systems.
return _storage.1.littleEndian
}
@inlinable @inline(__always)
internal var capacity: Int { return _SmallString.capacity }
@inlinable @inline(__always)
internal var count: Int {
return _StringObject.getSmallCount(fromRaw: rawDiscriminatedObject)
}
@inlinable @inline(__always)
internal var unusedCapacity: Int { return capacity &- count }
@inlinable @inline(__always)
internal var isASCII: Bool {
return _StringObject.getSmallIsASCII(fromRaw: rawDiscriminatedObject)
}
// Give raw, nul-terminated code units. This is only for limited internal
// usage: it always clears the discriminator and count (in case it's full)
@inlinable @inline(__always)
internal var zeroTerminatedRawCodeUnits: RawBitPattern {
#if os(Android) && arch(arm64)
let smallStringCodeUnitMask = ~UInt64(0xFFFF).bigEndian // zero last two bytes
#else
let smallStringCodeUnitMask = ~UInt64(0xFF).bigEndian // zero last byte
#endif
return (self._storage.0, self._storage.1 & smallStringCodeUnitMask)
}
internal func computeIsASCII() -> Bool {
let asciiMask: UInt64 = 0x8080_8080_8080_8080
let raw = zeroTerminatedRawCodeUnits
return (raw.0 | raw.1) & asciiMask == 0
}
}
// Internal invariants
extension _SmallString {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
_internalInvariant(count <= _SmallString.capacity)
_internalInvariant(isASCII == computeIsASCII())
// No bits should be set between the last code unit and the discriminator
var copy = self
withUnsafeBytes(of: ©._storage) {
_internalInvariant(
$0[count..<_SmallString.capacity].allSatisfy { $0 == 0 })
}
}
#endif // INTERNAL_CHECKS_ENABLED
internal func _dump() {
#if INTERNAL_CHECKS_ENABLED
print("""
smallUTF8: count: \(self.count), codeUnits: \(
self.map { String($0, radix: 16) }.joined()
)
""")
#endif // INTERNAL_CHECKS_ENABLED
}
}
// Provide a RAC interface
extension _SmallString: RandomAccessCollection, MutableCollection {
@usableFromInline
internal typealias Index = Int
@usableFromInline
internal typealias Element = UInt8
@usableFromInline
internal typealias SubSequence = _SmallString
@inlinable @inline(__always)
internal var startIndex: Int { return 0 }
@inlinable @inline(__always)
internal var endIndex: Int { return count }
@inlinable
internal subscript(_ idx: Int) -> UInt8 {
@inline(__always) get {
_internalInvariant(idx >= 0 && idx <= 15)
if idx < 8 {
return leadingRawBits._uncheckedGetByte(at: idx)
} else {
return trailingRawBits._uncheckedGetByte(at: idx &- 8)
}
}
@inline(__always) set {
_internalInvariant(idx >= 0 && idx <= 15)
if idx < 8 {
leadingRawBits._uncheckedSetByte(at: idx, to: newValue)
} else {
trailingRawBits._uncheckedSetByte(at: idx &- 8, to: newValue)
}
}
}
@inlinable @inline(__always)
internal subscript(_ bounds: Range<Index>) -> SubSequence {
get {
// TODO(String performance): In-vector-register operation
return self.withUTF8 { utf8 in
let rebased = UnsafeBufferPointer(rebasing: utf8[bounds])
return _SmallString(rebased)._unsafelyUnwrappedUnchecked
}
}
// This setter is required for _SmallString to be a valid MutableCollection.
// Since _SmallString is internal and this setter unused, we cheat.
@_alwaysEmitIntoClient set { fatalError() }
@_alwaysEmitIntoClient _modify { fatalError() }
}
}
extension _SmallString {
@inlinable @inline(__always)
internal func withUTF8<Result>(
_ f: (UnsafeBufferPointer<UInt8>) throws -> Result
) rethrows -> Result {
let count = self.count
var raw = self.zeroTerminatedRawCodeUnits
return try Swift._withUnprotectedUnsafeBytes(of: &raw) {
let rawPtr = $0.baseAddress._unsafelyUnwrappedUnchecked
// Rebind the underlying (UInt64, UInt64) tuple to UInt8 for the
// duration of the closure. Accessing self after this rebind is undefined.
let ptr = rawPtr.bindMemory(to: UInt8.self, capacity: count)
defer {
// Restore the memory type of self._storage
_ = rawPtr.bindMemory(to: RawBitPattern.self, capacity: 1)
}
return try f(UnsafeBufferPointer(_uncheckedStart: ptr, count: count))
}
}
// Overwrite stored code units, including uninitialized. `f` should return the
// new count. This will re-establish the invariant after `f` that all bits
// between the last code unit and the discriminator are unset.
@inline(__always)
fileprivate mutating func withMutableCapacity(
_ f: (UnsafeMutableRawBufferPointer) throws -> Int
) rethrows {
let len = try withUnsafeMutableBytes(of: &_storage, f)
if len <= 0 {
_debugPrecondition(len == 0)
self = _SmallString()
return
}
_SmallString.zeroTrailingBytes(of: &_storage, from: len)
self = _SmallString(leading: _storage.0, trailing: _storage.1, count: len)
}
@inlinable
@_alwaysEmitIntoClient
internal static func zeroTrailingBytes(
of storage: inout RawBitPattern, from index: Int
) {
_internalInvariant(index > 0)
_internalInvariant(index <= _SmallString.capacity)
//FIXME: Verify this on big-endian architecture
let mask0 = (UInt64(bitPattern: ~0) &>> (8 &* ( 8 &- Swift.min(index, 8))))
let mask1 = (UInt64(bitPattern: ~0) &>> (8 &* (16 &- Swift.max(index, 8))))
storage.0 &= (index <= 0) ? 0 : mask0.littleEndian
storage.1 &= (index <= 8) ? 0 : mask1.littleEndian
}
}
// Creation
extension _SmallString {
@inlinable @inline(__always)
internal init(leading: UInt64, trailing: UInt64, count: Int) {
_internalInvariant(count <= _SmallString.capacity)
let isASCII = (leading | trailing) & 0x8080_8080_8080_8080 == 0
let discriminator = _StringObject.Nibbles
.small(withCount: count, isASCII: isASCII)
.littleEndian // reversed byte order on big-endian platforms
_internalInvariant(trailing & discriminator == 0)
self.init(raw: (leading, trailing | discriminator))
_internalInvariant(self.count == count)
}
// Direct from UTF-8
@inlinable @inline(__always)
internal init?(_ input: UnsafeBufferPointer<UInt8>) {
if input.isEmpty {
self.init()
return
}
let count = input.count
guard count <= _SmallString.capacity else { return nil }
// TODO(SIMD): The below can be replaced with just be a masked unaligned
// vector load
let ptr = input.baseAddress._unsafelyUnwrappedUnchecked
let leading = _bytesToUInt64(ptr, Swift.min(input.count, 8))
let trailing = count > 8 ? _bytesToUInt64(ptr + 8, count &- 8) : 0
self.init(leading: leading, trailing: trailing, count: count)
}
@inline(__always)
internal init(
initializingUTF8With initializer: (
_ buffer: UnsafeMutableBufferPointer<UInt8>
) throws -> Int
) rethrows {
self.init()
try self.withMutableCapacity {
let capacity = $0.count
let rawPtr = $0.baseAddress._unsafelyUnwrappedUnchecked
// Rebind the underlying (UInt64, UInt64) tuple to UInt8 for the
// duration of the closure. Accessing self after this rebind is undefined.
let ptr = rawPtr.bindMemory(to: UInt8.self, capacity: capacity)
defer {
// Restore the memory type of self._storage
_ = rawPtr.bindMemory(to: RawBitPattern.self, capacity: 1)
}
return try initializer(
UnsafeMutableBufferPointer<UInt8>(start: ptr, count: capacity))
}
self._invariantCheck()
}
@usableFromInline // @testable
internal init?(_ base: _SmallString, appending other: _SmallString) {
let totalCount = base.count + other.count
guard totalCount <= _SmallString.capacity else { return nil }
// TODO(SIMD): The below can be replaced with just be a couple vector ops
var result = base
var writeIdx = base.count
for readIdx in 0..<other.count {
result[writeIdx] = other[readIdx]
writeIdx &+= 1
}
_internalInvariant(writeIdx == totalCount)
let (leading, trailing) = result.zeroTerminatedRawCodeUnits
self.init(leading: leading, trailing: trailing, count: totalCount)
}
}
#if _runtime(_ObjC) && !(arch(i386) || arch(arm) || arch(arm64_32))
// Cocoa interop
extension _SmallString {
// Resiliently create from a tagged cocoa string
//
@_effects(readonly) // @opaque
@usableFromInline // testable
internal init?(taggedCocoa cocoa: AnyObject) {
self.init()
var success = true
self.withMutableCapacity {
/*
For regular NSTaggedPointerStrings we will always succeed here, but
tagged NSLocalizedStrings may not fit in a SmallString
*/
if let len = _bridgeTagged(cocoa, intoUTF8: $0) {
return len
}
success = false
return 0
}
if !success {
return nil
}
self._invariantCheck()
}
}
#endif
extension UInt64 {
// Fetches the `i`th byte in memory order. On little-endian systems the byte
// at i=0 is the least significant byte (LSB) while on big-endian systems the
// byte at i=7 is the LSB.
@inlinable @inline(__always)
internal func _uncheckedGetByte(at i: Int) -> UInt8 {
_internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride)
#if _endian(big)
let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8
#else
let shift = UInt64(truncatingIfNeeded: i) &* 8
#endif
return UInt8(truncatingIfNeeded: (self &>> shift))
}
// Sets the `i`th byte in memory order. On little-endian systems the byte
// at i=0 is the least significant byte (LSB) while on big-endian systems the
// byte at i=7 is the LSB.
@inlinable @inline(__always)
internal mutating func _uncheckedSetByte(at i: Int, to value: UInt8) {
_internalInvariant(i >= 0 && i < MemoryLayout<UInt64>.stride)
#if _endian(big)
let shift = (7 - UInt64(truncatingIfNeeded: i)) &* 8
#else
let shift = UInt64(truncatingIfNeeded: i) &* 8
#endif
let valueMask: UInt64 = 0xFF &<< shift
self = (self & ~valueMask) | (UInt64(truncatingIfNeeded: value) &<< shift)
}
}
@inlinable @inline(__always)
internal func _bytesToUInt64(
_ input: UnsafePointer<UInt8>,
_ c: Int
) -> UInt64 {
// FIXME: This should be unified with _loadPartialUnalignedUInt64LE.
// Unfortunately that causes regressions in literal concatenation tests. (Some
// owned to guaranteed specializations don't get inlined.)
var r: UInt64 = 0
var shift: Int = 0
for idx in 0..<c {
r = r | (UInt64(input[idx]) &<< shift)
shift = shift &+ 8
}
// Convert from little-endian to host byte order.
return r.littleEndian
}
| apache-2.0 | 88593e25c9909c2410e7de420f037d19 | 31.750588 | 82 | 0.667649 | 4.12537 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.