repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
bvic23/VinceRP | VinceRP/Extension/UIKit/UIResponder+VinceRP.swift | 1 | 657 | //
// Created by Agnes Vasarhelyi on 30/10/15.
// Copyright (c) 2015 Viktor Belenyesi. All rights reserved.
//
import UIKit
public extension UIResponder {
public func reactiveProperty<T>(forProperty propertyName: String, initValue: T?, initializer: ((Source<T>) -> ())? = nil) -> Hub<T> {
return ReactivePropertyGenerator.instance.property(self, propertyName: propertyName, initValue: initValue, initializer: initializer)
}
public func reactiveSource<T>(name propertyName: String, initValue: T?) -> Source<T> {
return ReactivePropertyGenerator.instance.source(self, propertyName: propertyName, initValue: initValue)
}
}
| mit |
planvine/Line-Up-iOS-SDK | Pod/Classes/Line-Up_ExtCoreData.swift | 1 | 13005 | /**
* Copyright (c) 2016 Line-Up
*
* 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
import CoreData
extension LineUp {
//MARK: - CoreData methods
/**
* Get the event (PVEvent) with id: 'id' from CoreData.
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getEventFromCoreData(id: NSNumber) -> PVEvent? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVEvent, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"eventID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVEvent)!
}
} catch { return nil }
return nil
}
class func getVenueFromCoreData(id: NSNumber) -> PVVenue? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVVenue, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"venueID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVVenue)!
}
} catch { return nil }
return nil
}
/**
* Get the performance (PVPerformance) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getPerformanceFromCoreData(id: NSNumber) -> PVPerformance? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"performanceID = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVPerformance)!
}
} catch { return nil }
return nil
}
/**
* It returns true if the performance with id: 'id' has tickets, false otherwise
*/
class func performanceHasTickets(id: NSNumber) -> Bool {
var perf : PVPerformance? = getPerformanceFromCoreData(id)
if perf == nil {
perf = getPerformance(id)
}
if perf != nil && perf!.hasTickets == true {
return true
}
return false
}
/**
* Get the user (PVUser) with accessToken: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getUserWithTokenFromCoreData(userToken: String) -> PVUser? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVUser, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"accessToken = %@",userToken)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVUser)!
}
} catch { return nil }
return nil
}
/**
* Get the ticket (PVTicket) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
public class func getTicketFromCoreData(id: NSNumber) -> PVTicket? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVTicket, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVTicket)!
}
} catch { return nil }
return nil
}
/**
* Get the receipts (array of PVReceipt) for the usen with token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getTicketsReceiptsFromCoreData(userToken: String) -> [PVReceipt]? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"user.accessToken = %@",userToken)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
guard objects.count > 0 else {
return nil
}
return objects as? Array<PVReceipt>
} catch {
return nil
}
}
/**
* Get the receipt (PVReceipt) with id: 'id' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getReceiptFromCoreData(id: NSNumber) -> PVReceipt? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVReceipt, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
guard objects.count > 0 else {
return nil
}
return (objects.lastObject as? PVReceipt)
} catch {
return nil
}
}
/**
* Get list of tickets (array of PVTicket) available for the performance with id: 'performanceId' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getTicketsFromCoreDataOfPerformance(performanceId: NSNumber) -> [PVTicket] {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVPerformance, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"performanceID = %@",performanceId)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 && (objects.lastObject as! PVPerformance).tickets != nil && (objects.lastObject as! PVPerformance).tickets!.allObjects.count > 0{
return (objects.lastObject as? PVPerformance)!.tickets!.allObjects as! Array<PVTicket>
}
} catch { return Array() }
return Array()
}
/**
* Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getCardsFromCoreData(userToken: String) -> (NSFetchRequest, [PVCard]?) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false)
let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false)
let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false)
let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4]
fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@",userToken)
do {
return (fetchRequest,try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as? Array<PVCard>)
} catch {
return (fetchRequest,nil)
}
}
/**
* Get list of credit cards (array of PVCard for the user with Line-Up token: 'userToken' from CoreData
* - Note: This means that it doesn't GET the information from the Line-Up server, but it recovers them from the device.
*/
class func getCardFromCoreData(id: String) -> PVCard? {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
fetchRequest.predicate = NSPredicate(format:"id = %@",id)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
if objects.count > 0 {
return (objects.lastObject as? PVCard)!
}
} catch { return nil }
return nil
}
/**
* Delete all the credit cards from CoreData except the cards in 'listOfCards'
*/
public class func deleteCardsFromCoreDataExcept(listOfCards: Array<PVCard>, userToken: String) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
let sortDescriptor1 = NSSortDescriptor(key: "selectedCard", ascending: false)
let sortDescriptor2 = NSSortDescriptor(key: "brand", ascending: false)
let sortDescriptor3 = NSSortDescriptor(key: "expYear", ascending: false)
let sortDescriptor4 = NSSortDescriptor(key: "expMonth", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor1,sortDescriptor2,sortDescriptor3,sortDescriptor4]
var listOfIds: Array<String> = Array()
for card in listOfCards {
if card.id != nil {
listOfIds.append(card.id!)
}
}
fetchRequest.predicate = NSPredicate(format: "user.accessToken = %@ && NOT id IN %@",userToken, listOfIds)
do {
let objects : NSArray = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest)
for managedObject in objects {
PVCoreData.managedObjectContext.deleteObject(managedObject as! NSManagedObject)
}
try PVCoreData.managedObjectContext.save()
} catch { }
}
/**
* Set the card (PVCard) as selected card (default one) on the device (CoreData)
*/
public class func setSelectedCard(card: PVCard) {
let fetchRequest : NSFetchRequest = NSFetchRequest()
fetchRequest.entity = NSEntityDescription.entityForName(PVEntity.PVCard, inManagedObjectContext: PVCoreData.managedObjectContext)!
do {
let objects : Array<PVCard> = try PVCoreData.managedObjectContext.executeFetchRequest(fetchRequest) as! Array<PVCard>
for obj in objects {
if obj.id != card.id {
obj.selectedCard = false
} else {
obj.selectedCard = true
}
}
try PVCoreData.managedObjectContext.save()
} catch { }
}
}
| mit |
abbeycode/Nimble | Tests/NimbleTests/Matchers/BeAKindOfTest.swift | 6 | 3461 | import Foundation
import XCTest
import Nimble
private class TestNull: NSNull {}
private protocol TestProtocol {}
private class TestClassConformingToProtocol: TestProtocol {}
private struct TestStructConformingToProtocol: TestProtocol {}
final class BeAKindOfSwiftTest: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (BeAKindOfSwiftTest) -> () throws -> Void)] {
return [
("testPositiveMatch", testPositiveMatch),
("testFailureMessages", testFailureMessages),
]
}
enum TestEnum {
case one, two
}
func testPositiveMatch() {
expect(1).to(beAKindOf(Int.self))
expect(1).toNot(beAKindOf(String.self))
expect("turtle string").to(beAKindOf(String.self))
expect("turtle string").toNot(beAKindOf(TestClassConformingToProtocol.self))
expect(TestEnum.one).to(beAKindOf(TestEnum.self))
let testProtocolClass = TestClassConformingToProtocol()
expect(testProtocolClass).to(beAKindOf(TestClassConformingToProtocol.self))
expect(testProtocolClass).to(beAKindOf(TestProtocol.self))
expect(testProtocolClass).toNot(beAKindOf(TestStructConformingToProtocol.self))
let testProtocolStruct = TestStructConformingToProtocol()
expect(testProtocolStruct).to(beAKindOf(TestStructConformingToProtocol.self))
expect(testProtocolStruct).to(beAKindOf(TestProtocol.self))
expect(testProtocolStruct).toNot(beAKindOf(TestClassConformingToProtocol.self))
}
func testFailureMessages() {
failsWithErrorMessage("expected to not be a kind of Int, got <Int instance>") {
expect(1).toNot(beAKindOf(Int.self))
}
let testClass = TestClassConformingToProtocol()
failsWithErrorMessage("expected to not be a kind of \(String(describing: TestProtocol.self)), got <\(String(describing: TestClassConformingToProtocol.self)) instance>") {
expect(testClass).toNot(beAKindOf(TestProtocol.self))
}
failsWithErrorMessage("expected to be a kind of String, got <Int instance>") {
expect(1).to(beAKindOf(String.self))
}
}
}
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
final class BeAKindOfObjCTest: XCTestCase, XCTestCaseProvider {
static var allTests: [(String, (BeAKindOfObjCTest) -> () throws -> Void)] {
return [
("testPositiveMatch", testPositiveMatch),
("testFailureMessages", testFailureMessages),
]
}
func testPositiveMatch() {
expect(TestNull()).to(beAKindOf(NSNull.self))
expect(NSObject()).to(beAKindOf(NSObject.self))
expect(NSNumber(value: 1)).toNot(beAKindOf(NSDate.self))
}
func testFailureMessages() {
failsWithErrorMessageForNil("expected to not be a kind of NSNull, got <nil>") {
expect(nil as NSNull?).toNot(beAKindOf(NSNull.self))
}
failsWithErrorMessageForNil("expected to be a kind of NSString, got <nil>") {
expect(nil as NSString?).to(beAKindOf(NSString.self))
}
failsWithErrorMessage("expected to be a kind of NSString, got <__NSCFNumber instance>") {
expect(NSNumber(value: 1)).to(beAKindOf(NSString.self))
}
failsWithErrorMessage("expected to not be a kind of NSNumber, got <__NSCFNumber instance>") {
expect(NSNumber(value: 1)).toNot(beAKindOf(NSNumber.self))
}
}
}
#endif
| apache-2.0 |
sersoft-gmbh/AutoLayout_Macoun16 | AutoLayoutTricks/Invisible Layouts/GoodViewController.swift | 1 | 443 | //
// GoodViewController.swift
// Invisible Layouts
//
// Created by Daniel Friedrich on 16/09/16.
// Copyright © 2016 ser.soft GmbH. All rights reserved.
//
import UIKit
import FFUIKit
import FFFoundation
class GoodViewController: BadViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Fix it
}
}
| mit |
psharanda/SilverMVC | SilverMVC/WindowProtocol.swift | 1 | 306 | //
// Created by Pavel Sharanda on 19.03.17.
// Copyright © 2017 psharanda. All rights reserved.
//
import Foundation
protocol WindowProtocol: ViewProtocol {
var rootView: ViewProtocol? {get set}
func makeKeyAndVisible()
}
protocol WindowContainer {
func makeWindow() -> WindowProtocol
}
| mit |
eure/RealmIncrementalStore | RealmIncrementalStore/NSManagedObjectID+RealmIncrementalStore.swift | 1 | 1760 | //
// NSManagedObjectID+RealmIncrementalStore.swift
// RealmIncrementalStore
//
// Copyright © 2016 eureka, Inc., John Rommel Estropia
//
// 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 CoreData
import Foundation
import Realm
// MARK: - NSManagedObjectID
internal extension NSManagedObjectID {
func realmObject() -> RLMObject? {
guard case (let store as RealmIncrementalStore) = self.persistentStore else {
return nil
}
let primaryKey = store.referenceObjectForObjectID(self)
let backingClass = self.entity.realmBackingClass
return backingClass.init(inRealm: store.rootRealm, forPrimaryKey: primaryKey)
}
}
| mit |
watson-developer-cloud/ios-sdk | Sources/NaturalLanguageUnderstandingV1/Models/EmotionResult.swift | 1 | 1324 | /**
* (C) Copyright IBM Corp. 2017, 2020.
*
* 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
/**
The detected anger, disgust, fear, joy, or sadness that is conveyed by the content. Emotion information can be returned
for detected entities, keywords, or user-specified target phrases found in the text.
*/
public struct EmotionResult: Codable, Equatable {
/**
Emotion results for the document as a whole.
*/
public var document: DocumentEmotionResults?
/**
Emotion results for specified targets.
*/
public var targets: [TargetedEmotionResults]?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case document = "document"
case targets = "targets"
}
}
| apache-2.0 |
wftllc/hahastream | Haha Stream/HahaService/Models/DeviceKey.swift | 1 | 532 | import Foundation
class DeviceKey: NSObject, FromDictable {
public var key: String;
public var dict: [String: Any]
static func fromDictionary(_ dict:[String: Any]?) throws -> Self {
guard let dict = dict else { throw FromDictableError.keyError(key: "<root>") }
let key:String = try dict.value("key")
return self.init(key: key, dict: dict);
}
required public init(key: String, dict: [String: Any]) {
self.key = key;
self.dict = dict
}
override var description : String {
return "\(key); \(dict)";
}
}
| mit |
swift-tweets/tweetup-kit | Sources/TweetupKit/NSRegularExpressionExtensions.swift | 1 | 232 | import Foundation
extension NSRegularExpression {
internal func matches(in string: String) -> [NSTextCheckingResult] {
return matches(in: string, options: [], range: NSMakeRange(0, (string as NSString).length))
}
}
| mit |
ringohub/swift-todo | ToDoTests/ToDoTests.swift | 1 | 746 | import UIKit
import XCTest
class ToDoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
IDLabs-Gate/enVision | enVision/kNN.swift | 2 | 2285 | //
// The MIT License (MIT)
//
// Copyright (c) 2016 ID Labs L.L.C.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
class KNN {
private let kNN = tfkNN()
private var loaded = false
func load(){
kNN.loadModel("kNN.pb")
loaded = true
}
func run(x: [Double], samples: [[Double]], classes: [Int]) -> (Int, Double){
guard classes.count>0 && samples.count==classes.count else { return (-1,0) }
if !loaded { load() }
//choosing k = n^(1/2), but not more than the min count/2 of samples in a class
let minCount = Set(classes).map { c in classes.filter { $0==c }.count }.min{ a,b in a<b }!
var k = Int(sqrt(Double(samples.count)))
if k>minCount/2 { k = minCount/2 }
if k<1 { k = 1 }
print ("K", k)
let c = kNN.classify(x, samples: samples, classes: classes, k: Int32(k))
guard let pred = c?.first?.key as? Int else { return (-1,0) }
guard let dist = c?.first?.value as? Double else { return (-1,0) }
return (pred,dist)
}
func clean(){
kNN.clean()
loaded = false;
}
}
| mit |
lcddhr/DouyuTV | DouyuTV/Vender/DDKit/UIimage/UIImage+Asset.swift | 2 | 1055 | //
// UIImage+Asset.swift
// DouyuTV
//
// Created by lovelydd on 16/1/14.
// Copyright © 2016年 xiaomutou. All rights reserved.
//
import Foundation
import UIKit
extension UIImage {
enum Asset : String {
case Btn_search = "btn_search"
case Btn_search_clicked = "btn_search_clicked"
case Image_scan = "Image_scan"
case Image_scan_click = "Image_scan_click"
case Logo = "logo"
case S_logo = "s_logo"
case Btn_column_normal = "btn_column_normal"
case Btn_column_selected = "btn_column_selected"
case Btn_home_normal = "btn_home_normal"
case Btn_home_selected = "btn_home_selected"
case Btn_live_normal = "btn_live_normal"
case Btn_live_selected = "btn_live_selected"
case Btn_user_normal = "btn_user_normal"
case Btn_user_selected = "btn_user_selected"
var image: UIImage {
return UIImage(asset: self)
}
}
convenience init!(asset: Asset) {
self.init(named: asset.rawValue)
}
} | mit |
iqingchen/DouYuZhiBo | DY/DY/Classes/Home/Controller/GameViewController.swift | 1 | 4771 | //
// GameViewController.swift
// DY
//
// Created by zhang on 16/12/6.
// Copyright © 2016年 zhang. All rights reserved.
//
import UIKit
//MARK: - 定义常量
private let kEdgeMargin : CGFloat = 10
private let kItemW : CGFloat = (kScreenW - 2 * kEdgeMargin) / 3
private let kItemH : CGFloat = kItemW * 6 / 5
private let kHeaderViewH : CGFloat = 50
private let kGameViewH : CGFloat = 90
private let kGameCellID : String = "kGameCellID"
private let kReusableViewHeadID : String = "kReusableViewHeadID"
class GameViewController: BaseViewController {
//MARK: - 懒加载
fileprivate lazy var gameViewModel : GameViewModel = GameViewModel()
fileprivate lazy var commonHeaderView : CollectionHeaderView = {
let header = CollectionHeaderView.collectionHeaderView()
header.frame = CGRect(x: 0, y: -(kHeaderViewH + kGameViewH), width: kScreenW, height: kHeaderViewH)
header.titleLabel.text = "常见"
header.iconImageView.image = UIImage(named: "Img_orange")
header.moreBtn.isHidden = true
return header
}()
fileprivate lazy var recommendGameView : RecommendGameView = {
let gameView = RecommendGameView.createRecommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
fileprivate lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kItemH)
layout.sectionInset = UIEdgeInsetsMake(0, kEdgeMargin, 0, kEdgeMargin)
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.backgroundColor = UIColor.white
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kReusableViewHeadID)
return collectionView
}()
//MARK: - 系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置ui
setupUI()
//网络请求
requestData()
}
}
//MARK: - 设置UI
extension GameViewController {
override func setupUI() {
contentView = collectionView
//添加collectionView
view.addSubview(collectionView)
//添加常见header
collectionView.addSubview(commonHeaderView)
//添加常见游戏View
collectionView.addSubview(recommendGameView)
collectionView.contentInset = UIEdgeInsetsMake(kHeaderViewH + kGameViewH, 0, 0, 0)
super.setupUI()
}
}
//MARK: - 网络请求
extension GameViewController {
fileprivate func requestData() {
gameViewModel.loadAllGanmesData {
//1.刷新表格
self.collectionView.reloadData()
//2.讲数据传给recommendGameView
self.recommendGameView.baseGameModel = Array(self.gameViewModel.games[0..<10])
//数据请求完成
self.loadDataFinished()
}
}
}
//MARK: - 实现collectionView的数据源方法
extension GameViewController : UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return gameViewModel.games.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionGameCell
cell.baseGame = gameViewModel.games[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kReusableViewHeadID, for: indexPath) as! CollectionHeaderView
let group = AnchorGroup()
group.tag_name = "全部"
group.icon_name = "Img_orange"
header.group = group
header.moreBtn.isHidden = true
return header
}
}
| mit |
khizkhiz/swift | test/SILOptimizer/definite_init_failable_initializers_diagnostics.swift | 2 | 2561 | // RUN: %target-swift-frontend -emit-sil -disable-objc-attr-requires-foundation-module -verify %s
// High-level tests that DI rejects certain invalid idioms for early
// return from initializers.
// <rdar://problem/19267795> failable initializers that call noreturn function produces bogus diagnostics
class FailableInitThatFailsReallyHard {
init?() { // no diagnostics generated.
fatalError("bad")
}
}
class BaseClass {}
final class DerivedClass : BaseClass {
init(x : ()) {
fatalError("bad") // no diagnostics.
}
}
func something(x: Int) {}
func something(x: inout Int) {}
func something(x: AnyObject) {}
func something(x: Any.Type) {}
// <rdar://problem/22946400> DI needs to diagnose self usages in error block
//
// FIXME: crappy QoI
class ErrantBaseClass {
init() throws {}
}
class ErrantClass : ErrantBaseClass {
let x: Int
var y: Int
override init() throws {
x = 10
y = 10
try super.init()
}
init(invalidEscapeDesignated: ()) {
x = 10
y = 10
do {
try super.init()
} catch {}
} // expected-error {{'self' used inside 'catch' block reachable from super.init call}}
convenience init(invalidEscapeConvenience: ()) {
do {
try self.init()
} catch {}
} // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
init(noEscapeDesignated: ()) throws {
x = 10
y = 10
do {
try super.init()
} catch let e {
throw e // ok
}
}
convenience init(noEscapeConvenience: ()) throws {
do {
try self.init()
} catch let e {
throw e // ok
}
}
convenience init(invalidAccess: ()) throws {
do {
try self.init()
} catch let e {
something(x) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(self.x) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(self.y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(&y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(&self.y) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
something(self) // expected-error {{'self' used inside 'catch' block reachable from self.init call}}
// FIXME: not diagnosed
something(self.dynamicType)
throw e
}
}
}
| apache-2.0 |
khizkhiz/swift | test/ClangModules/objc_init.swift | 2 | 4584 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-sil -I %S/Inputs/custom-modules %s -verify
// REQUIRES: objc_interop
// REQUIRES: OS=macosx
// FIXME: <rdar://problem/19452886> test/ClangModules/objc_init.swift should not require REQUIRES: OS=macosx
import AppKit
import objc_ext
import TestProtocols
import ObjCParseExtras
// rdar://problem/18500201
extension NSSet {
convenience init<T>(array: Array<T>) {
self.init()
}
}
// Subclassing and designated initializers
func testNSInterestingDesignated() {
NSInterestingDesignated() // expected-warning{{unused}}
NSInterestingDesignated(string:"hello") // expected-warning{{unused}}
NSInterestingDesignatedSub() // expected-warning{{unused}}
NSInterestingDesignatedSub(string:"hello") // expected-warning{{unused}}
}
extension URLDocument {
convenience init(string: String) {
self.init(url: string)
}
}
class MyDocument1 : URLDocument {
override init() {
super.init()
}
}
func createMyDocument1() {
var md = MyDocument1()
md = MyDocument1(url: "http://llvm.org")
// Inherited convenience init.
md = MyDocument1(string: "http://llvm.org")
_ = md
}
class MyDocument2 : URLDocument {
init(url: String) {
super.init(url: url) // expected-error{{must call a designated initializer of the superclass 'URLDocument'}}
}
}
class MyDocument3 : NSAwesomeDocument {
override init() {
super.init()
}
}
func createMyDocument3(url: NSURL) {
var md = MyDocument3()
md = try! MyDocument3(contentsOf: url, ofType:"")
_ = md
}
class MyInterestingDesignated : NSInterestingDesignatedSub {
override init(string str: String) {
super.init(string: str)
}
init(int i: Int) {
super.init() // expected-error{{must call a designated initializer of the superclass 'NSInterestingDesignatedSub'}}
}
}
func createMyInterestingDesignated() {
_ = MyInterestingDesignated(url: "http://llvm.org")
}
func testNoReturn(a : NSAwesomeDocument) -> Int {
a.noReturnMethod(42)
return 17 // TODO: In principle, we should produce an unreachable code diagnostic here.
}
// Initializer inheritance from protocol-specified initializers.
class MyViewController : NSViewController {
}
class MyView : NSView {
override init() { super.init() }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSView'}}
class MyMenu : NSMenu {
override init(title: String) { super.init(title: title) }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSMenu'}}
class MyTableViewController : NSTableViewController {
}
class MyOtherTableViewController : NSTableViewController {
override init(int i: Int) {
super.init(int: i)
}
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSTableViewController'}}
class MyThirdTableViewController : NSTableViewController {
override init(int i: Int) {
super.init(int: i)
}
required init(coder: NSCoder) {
super.init(coder: coder)!
}
}
func checkInitWithCoder(coder: NSCoder) {
NSViewController(coder: coder) // expected-warning{{unused}}
NSTableViewController(coder: coder) // expected-warning{{unused}}
MyViewController(coder: coder) // expected-warning{{unused}}
MyTableViewController(coder: coder) // expected-warning{{unused}}
MyOtherTableViewController(coder: coder) // expected-error{{incorrect argument label in call (have 'coder:', expected 'int:')}}
MyThirdTableViewController(coder: coder) // expected-warning{{unused}}
}
// <rdar://problem/16838409>
class MyDictionary1 : NSDictionary {}
func getMyDictionary1() {
_ = MyDictionary1()
}
// <rdar://problem/16838515>
class MyDictionary2 : NSDictionary {
override init() {
super.init()
}
}
class MyString : NSString {
override init() { super.init() }
} // expected-error{{'required' initializer 'init(coder:)' must be provided by subclass of 'NSString'}}
// <rdar://problem/17281900>
class View: NSView {
override func addSubview(aView: NSView) {
_ = MyViewController.init()
}
}
// rdar://problem/19726164
class NonNullDefaultInitSubSub : NonNullDefaultInitSub {
func foo() {
_ = NonNullDefaultInitSubSub() as NonNullDefaultInitSubSub?
}
}
class DesignatedInitSub : DesignatedInitBase {
var foo: Int?
override init(int: Int) {}
}
class DesignedInitSubSub : DesignatedInitSub {
init(double: Double) { super.init(int: 0) } // okay
init(string: String) { super.init() } // expected-error {{must call a designated initializer of the superclass 'DesignatedInitSub'}}
}
| apache-2.0 |
amolloy/LinkAgainstTheWorld | Frameworks/TileMap/TileMap/Layer.swift | 2 | 2344 | //
// Layer.swift
// TileMap
//
// Created by Andrew Molloy on 8/9/15.
// Copyright © 2015 Andrew Molloy. All rights reserved.
//
import Foundation
protocol Tileable
{
}
class Layer : Loadable
{
var chunkType : ChunkType?
let tiles : [[Tileable]]
required init?(inputStream: NSInputStream, dataLength: Int, tileMap: TileMap, chunkType: ChunkType)
{
guard let mapHeader = tileMap.mapHeader,
let blockData = tileMap.blockData,
let animationData = tileMap.animationData else
{
tiles = [[Tileable]]()
return nil
}
let swapBytes = mapHeader.swapBytes
var tileRows = [[Tileable]]()
if mapHeader.mapType == .FMP05
{
for _ in 0..<mapHeader.mapSize.height
{
var tileColumns = [Tileable]()
for _ in 0..<mapHeader.mapSize.width
{
guard let tile = inputStream.readInt16(swapBytes) else
{
tiles = [[Tileable]]()
return nil
}
if tile >= 0
{
let theIndex = Int(tile) / mapHeader.blockStructureSize
tileColumns.append(blockData.blockStructures[theIndex])
}
else
{
let divisor : Int
if .FMP05 == mapHeader.mapType
{
divisor = 16
}
else
{
divisor = 1
}
let theIndex = Int(-tile) / divisor - 1
tileColumns.append(animationData.animationStructures[theIndex])
}
}
tileRows.append(tileColumns)
}
}
else if mapHeader.mapType == .FMP10
{
// TODO
assert(false, "FMP 1.0 Maps not yet implemented")
}
else if mapHeader.mapType == .FMP10RLE
{
// TODO
assert(false, "FMP 1.0RLE Maps not yet implemented")
}
else
{
// TODO Throw too new (shouldn't even get here in that case)
tiles = [[Tileable]]()
return nil
}
tiles = tileRows
tileMap.addLayer(self, index: chunkType.layer())
}
static func registerWithTileMap(tileMap: TileMap)
{
tileMap.registerLoadable(self, chunkType: ChunkType.BODY)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR1)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR2)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR3)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR4)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR5)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR6)
tileMap.registerLoadable(self, chunkType: ChunkType.LYR7)
}
}
| mit |
aliceatlas/hexagen | Hexagen/Swift/Task/GeneratorTask.swift | 1 | 1197 | /*****\\\\
/ \\\\ Swift/Task/GeneratorTask.swift
/ /\ /\ \\\\ (part of Hexagen)
\ \_X_/ ////
\ //// Copyright © 2015 Alice Atlas (see LICENSE.md)
\*****////
public final class AsyncGen<OutType, ReturnType>: Async<ReturnType> {
private let feed: Feed<OutType>
public init(queue: dispatch_queue_t = mainQueue, body: (OutType -> Void) -> ReturnType) {
var post: (OutType -> Void)!
var end: (Void -> Void)!
feed = Feed<OutType> { (_post, _end) in
post = _post
end = _end
}
super.init(queue: queue, start: false, body: {
let ret = body(post!)
end()
return ret
})
}
}
extension AsyncGen: SequenceType {
public func generate() -> Subscription<OutType> {
let gen = feed.generate()
if !started {
start()
}
return gen
}
public func map<T>(fn: OutType -> T) -> LazySequence<MapSequenceView<AsyncGen, T>> {
return lazy(self).map(fn)
}
public func filter(fn: OutType -> Bool) -> LazySequence<FilterSequenceView<AsyncGen>> {
return lazy(self).filter(fn)
}
}
| mit |
wufeiyue/FYShareView | FYShareView/AppDelegate.swift | 1 | 2180 | //
// AppDelegate.swift
// FYShareView
//
// Created by 武飞跃 on 2017/10/24.
// Copyright © 2017年 wufeiyue.com. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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 |
manGoweb/S3 | Sources/S3Kit/URLBuilder/S3URLBuilder.swift | 1 | 1772 | import Foundation
import S3Signer
/// URL builder
public final class S3URLBuilder: URLBuilder {
/// Default bucket
let defaultBucket: String
/// S3 Configuration
let config: S3Signer.Config
/// Initializer
public init(defaultBucket: String, config: S3Signer.Config) {
self.defaultBucket = defaultBucket
self.config = config
}
/// Plain Base URL with no bucket specified
/// *Format: https://s3.eu-west-2.amazonaws.com/
public func plain(region: Region? = nil) throws -> URL {
let urlString = (region ?? config.region).hostUrlString()
guard let url = URL(string: urlString) else {
throw S3.Error.invalidUrl
}
return url
}
/// Base URL for S3 region
/// *Format: https://bucket.s3.eu-west-2.amazonaws.com/path_or_parameter*
public func url(region: Region? = nil, bucket: String? = nil, path: String? = nil) throws -> URL {
let urlString = (region ?? config.region).hostUrlString(bucket: (bucket ?? defaultBucket))
guard let url = URL(string: urlString) else {
throw S3.Error.invalidUrl
}
return url
}
/// Base URL for a file in a bucket
/// * Format: https://s3.eu-west-2.amazonaws.com/bucket/file.txt
/// * We can't have a bucket in the host or DELETE will attempt to delete the bucket, not file!
public func url(file: LocationConvertible) throws -> URL {
let urlString = (file.region ?? config.region).hostUrlString()
guard let url = URL(string: urlString)?.appendingPathComponent(file.bucket ?? defaultBucket).appendingPathComponent(file.path) else {
throw S3.Error.invalidUrl
}
return url
}
}
| mit |
Mindera/Alicerce | Tests/AlicerceTests/StackOrchestrator/StackOrchestratorTestCase.swift | 1 | 505 | import XCTest
@testable import Alicerce
class StackOrchestratorTestCase: XCTestCase {
typealias FetchValue = StackOrchestrator.FetchValue<Int, String>
func testValue_WithNetworkFetchValue_ShouldReturnValue() throws {
let value = FetchValue.network(1337, "🌍")
XCTAssertEqual(value.value, 1337)
}
func testValue_WithPersistenceFetchValue_ShouldReturnValue() throws {
let value = FetchValue.persistence(1337)
XCTAssertEqual(value.value, 1337)
}
}
| mit |
ahayman/RxStream | RxStreamTests/ArrayExtensionsTests.swift | 1 | 1426 | //
// ArrayExtensionsTests.swift
// RxStream
//
// Created by Aaron Hayman on 4/21/17.
// Copyright © 2017 Aaron Hayman. All rights reserved.
//
import XCTest
@testable import Rx
class ArrayExtensionsTests: XCTestCase {
func testIndexOf() {
let array = [0, 1, 2, 3, 4, 5, 6]
XCTAssertEqual(array.indexOf{ $0 == 3 }, 3)
XCTAssertEqual(array.indexOf{ $0 == 5 }, 5)
let strings = ["hello", "world", "1", "2", "3"]
XCTAssertEqual(strings.indexOf{ $0 == "world" }, 1)
XCTAssertEqual(strings.indexOf{ $0 == "2" }, 3)
XCTAssertNil(strings.indexOf{ $0 == "4" })
}
func testRemoving() {
XCTAssertEqual([0, 0, 1, 1, 1, 1, 0, 0, 1].removing([1]), [0, 0, 0, 0])
XCTAssertEqual([0, 0, 1, 1, 1, 1, 0, 0, 1].removing([0]), [1, 1, 1, 1, 1])
XCTAssertEqual(["hello", "world", "world", "1", "2", "3"].removing(["world", "2", "3"]), ["hello", "1"])
}
func testTakeUntil() {
XCTAssertEqual([0, 1, 2, 3, 4, 5].takeUntil{ $0 == 3 }, [0, 1, 2])
XCTAssertEqual([0, 1, 2, 3, 4, 5].takeUntil{ $0 == 5 }, [0, 1, 2, 3, 4])
XCTAssertEqual([0, 1, 2, 3, 4, 5].takeUntil{ $0 == 10 }, [0, 1, 2, 3, 4, 5])
}
func testOMap() {
XCTAssertEqual([0, 1, 2, 3, 4, 5].oMap{ $0 % 2 == 0 ? $0 : nil }, [0, 2, 4])
XCTAssertEqual([0, 1, 2, 3, 4, 5].oMap{ $0 % 2 == 1 ? $0 : nil }, [1, 3, 5])
}
func testFilled() {
XCTAssertNil([].filled)
XCTAssertNotNil([1].filled)
}
}
| mit |
johndpope/Cerberus | Cerberus/Classes/TimelineCollectionViewController.swift | 1 | 5379 | import UIKit
import Timepiece
class TimelineCollectionViewController: UICollectionViewController {
var timeArray = [String]()
private var timer: NSTimer?
private let timerTickIntervalSec = 60.0
override func viewDidLoad() {
super.viewDidLoad()
generateTimeLabels()
collectionView?.showsVerticalScrollIndicator = false
let nib = UINib(nibName: XibNames.TimeCollectionViewCell.rawValue, bundle: nil)
self.collectionView?.registerNib(nib, forCellWithReuseIdentifier: CollectionViewCellreuseIdentifier.TimeCell.rawValue)
self.timer = NSTimer.scheduledTimerWithTimeInterval(timerTickIntervalSec, target: self, selector: "onTimerTick:", userInfo: nil, repeats: true)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "didUpdateTimelineNotification:",
name: NotifictionNames.TimelineCollectionViewControllerDidUpdateTimelineNotification.rawValue,
object: nil
)
}
deinit {
self.timer?.invalidate()
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private func generateTimeLabels() {
let now = NSDate()
var date = now.beginningOfDay
while date < now.endOfDay {
var nextDate = date + 30.minutes
timeArray.append(date.stringFromFormat("HH:mm"))
if date < now && now < nextDate {
// timeArray.append(now.stringFromFormat("HH:mm")) // TODO
}
date = nextDate
}
timeArray.append("24:00")
}
func didUpdateTimelineNotification(notification: NSNotification) {
scrollToCurrentTime()
}
override func viewDidAppear(animated: Bool) {
scrollToCurrentTime()
}
// MARK: UICollectionViewDataSource
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return timeArray.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let reuseIdentifier = CollectionViewCellreuseIdentifier.TimeCell.rawValue
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! TimeCollectionViewCell
cell.timeLabel.text = timeArray[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let timelineCollectionViewFlowLayout = collectionViewLayout as! TimelineCollectionViewFlowLayout
return timelineCollectionViewFlowLayout.sizeForTimeline()
}
// MARK: UIScrollViewDelegate
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
scrollToCenteredCell()
}
override func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if !decelerate {
scrollToCenteredCell()
}
}
// MARK: Private
private func scrollToCenteredCell() {
let point = CGPointMake(collectionView!.center.x, collectionView!.center.y + collectionView!.contentOffset.y)
if let centeredIndexPath = collectionView?.indexPathForItemAtPoint(point) {
collectionView?.scrollToItemAtIndexPath(centeredIndexPath, atScrollPosition: .CenteredVertically, animated: true)
}
}
private func scrollToCurrentTime() {
let date = NSDate()
let newIndex = NSIndexPath(forItem: (date.hour * 60 + date.minute) / 30, inSection: 0)
self.collectionView?.scrollToItemAtIndexPath(newIndex, atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let (visibles, nearestCenter) = getVisibleCellsAndNearestCenterCell()
let timelineCollectionViewFlowLayout = self.collectionViewLayout as! TimelineCollectionViewFlowLayout
for cellInfo in visibles {
let cell = cellInfo.cell as! TimeCollectionViewCell
cell.hidden = false
let time = self.timeArray[cellInfo.row]
var dy: CGFloat = 0.0
var height: CGFloat = timelineCollectionViewFlowLayout.sizeForTimeline().height
var alpha: CGFloat = 0.0
if cell == nearestCenter.cell {
height += TimelineHeight
alpha = 1.0
cell.makeLabelBold()
} else {
dy = (cellInfo.row < nearestCenter.row ? -1 : +1) * TimelineHeight / 2
alpha = 0.5
cell.makeLabelNormal()
}
UIView.animateWithDuration(0.6,
delay: 0.0,
usingSpringWithDamping: 0.5,
initialSpringVelocity: 0.0,
options: .CurveEaseInOut,
animations: { () -> Void in
cell.bounds.size.height = height
cell.transform = CGAffineTransformMakeTranslation(0, dy)
cell.alpha = alpha
},
completion: nil
)
}
}
// MARK: timer
func onTimerTick(timer: NSTimer) {
scrollToCurrentTime()
}
}
| mit |
Swift3Home/Swift3_Object-oriented | 005-OC{}的一个坑/005-OC{}的一个坑/ViewController.swift | 1 | 785 | //
// ViewController.swift
// 005-OC{}的一个坑
//
// Created by lichuanjun on 2017/5/31.
// Copyright © 2017年 lichuanjun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let lbl = UILabel()
// (lbl) 参数结束 { 尾随闭包 }
view.addSubview(lbl);
//Extra argument in call:调用了额外的参数
// {
let lbl = UILabel()
view.addSubview(lbl)
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
AnirudhDas/AniruddhaDas.github.io | GuessImageGame/GuessImageGame/Configurations/Constants.swift | 1 | 764 | import Foundation
import UIKit
//MARK:- Storyboard
public let CollectionViewCellIdentifier = "ImageCell"
//MARK:- Other Configurable Parameters
public let MAX_NUMBER_OF_IMAGES = 9
public let STARTING_TIME: TimeInterval = 15
public let GUESS_WHERE_THIS_PHTO_WAS = "Guess where this photo was"
public let PLAY_AGAIN = "Play Again"
public let NAVIGATION_BAR_TITLE = "Guess the Image"
public let SPINNER_TITLE = "Please wait..."
public let ALERT_TITLE = "Congrats!"
public let ALERT_MESSAGE = "Your guess is correct."
public let ALERT_BUTTON_TITLE = "OK"
//MARK:- Images
public let PLACEHOLDER = #imageLiteral(resourceName: "placeholder")
public let FLIPPED = #imageLiteral(resourceName: "flipped")
public let BACKGROUND = #imageLiteral(resourceName: "background")
| apache-2.0 |
netprotections/atonecon-ios | AtoneCon/Sources/NetworkReachabilityManager.swift | 1 | 7949 | #if !os(watchOS)
import Foundation
import SystemConfiguration
/// The `NetworkReachabilityManager` class listens for reachability changes of hosts and addresses for both WWAN and
/// WiFi network interfaces.
///
/// Reachability can be used to determine background information about why a network operation failed, or to retry
/// network requests when a connection is established. It should not be used to prevent a user from initiating a network
/// request, as it's possible that an initial request may be required to establish reachability.
internal class NetworkReachabilityManager {
/// Defines the various states of network reachability.
///
/// - unknown: It is unknown whether the network is reachable.
/// - notReachable: The network is not reachable.
/// - reachable: The network is reachable.
internal enum NetworkReachabilityStatus {
case unknown
case notReachable
case reachable(ConnectionType)
}
/// Defines the various connection types detected by reachability flags.
///
/// - ethernetOrWiFi: The connection type is either over Ethernet or WiFi.
/// - wwan: The connection type is a WWAN connection.
internal enum ConnectionType {
case ethernetOrWiFi
case wwan
}
/// A closure executed when the network reachability status changes. The closure takes a single argument: the
/// network reachability status.
internal typealias Listener = (NetworkReachabilityStatus) -> Void
// MARK: - Properties
/// Whether the network is currently reachable.
internal var isReachable: Bool { return isReachableOnWWAN || isReachableOnEthernetOrWiFi }
/// Whether the network is currently reachable over the WWAN interface.
internal var isReachableOnWWAN: Bool { return networkReachabilityStatus == .reachable(.wwan) }
/// Whether the network is currently reachable over Ethernet or WiFi interface.
internal var isReachableOnEthernetOrWiFi: Bool { return networkReachabilityStatus == .reachable(.ethernetOrWiFi) }
/// The current network reachability status.
internal var networkReachabilityStatus: NetworkReachabilityStatus {
guard let flags = self.flags else { return .unknown }
return networkReachabilityStatusForFlags(flags)
}
/// The dispatch queue to execute the `listener` closure on.
internal var listenerQueue: DispatchQueue = DispatchQueue.main
/// A closure executed when the network reachability status changes.
internal var listener: Listener?
private var flags: SCNetworkReachabilityFlags? {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(reachability, &flags) {
return flags
}
return nil
}
private let reachability: SCNetworkReachability
private var previousFlags: SCNetworkReachabilityFlags
// MARK: - Initialization
/// Creates a `NetworkReachabilityManager` instance with the specified host.
///
/// - parameter host: The host used to evaluate network reachability.
///
/// - returns: The new `NetworkReachabilityManager` instance.
internal convenience init?(host: String) {
guard let reachability = SCNetworkReachabilityCreateWithName(nil, host) else { return nil }
self.init(reachability: reachability)
}
/// Creates a `NetworkReachabilityManager` instance that monitors the address 0.0.0.0.
///
/// Reachability treats the 0.0.0.0 address as a special token that causes it to monitor the general routing
/// status of the device, both IPv4 and IPv6.
///
/// - returns: The new `NetworkReachabilityManager` instance.
internal convenience init?() {
var address = sockaddr_in()
address.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
address.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &address, { pointer in
return pointer.withMemoryRebound(to: sockaddr.self, capacity: MemoryLayout<sockaddr>.size) {
return SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else { return nil }
self.init(reachability: reachability)
}
private init(reachability: SCNetworkReachability) {
self.reachability = reachability
self.previousFlags = SCNetworkReachabilityFlags()
}
deinit {
stopListening()
}
// MARK: - Listening
/// Starts listening for changes in network reachability status.
///
/// - returns: `true` if listening was started successfully, `false` otherwise.
@discardableResult
internal func startListening() -> Bool {
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = Unmanaged.passUnretained(self).toOpaque()
let callbackEnabled = SCNetworkReachabilitySetCallback(
reachability, { (_, flags, info) in
if let info = info {
let reachability = Unmanaged<NetworkReachabilityManager>.fromOpaque(info).takeUnretainedValue()
reachability.notifyListener(flags)
}
},
&context
)
let queueEnabled = SCNetworkReachabilitySetDispatchQueue(reachability, listenerQueue)
listenerQueue.async {
self.previousFlags = SCNetworkReachabilityFlags()
self.notifyListener(self.flags ?? SCNetworkReachabilityFlags())
}
return callbackEnabled && queueEnabled
}
/// Stops listening for changes in network reachability status.
internal func stopListening() {
SCNetworkReachabilitySetCallback(reachability, nil, nil)
SCNetworkReachabilitySetDispatchQueue(reachability, nil)
}
// MARK: - Internal - Listener Notification
internal func notifyListener(_ flags: SCNetworkReachabilityFlags) {
guard previousFlags != flags else { return }
previousFlags = flags
listener?(networkReachabilityStatusForFlags(flags))
}
// MARK: - Internal - Network Reachability Status
internal func networkReachabilityStatusForFlags(_ flags: SCNetworkReachabilityFlags) -> NetworkReachabilityStatus {
guard isNetworkReachable(with: flags) else { return .notReachable }
var networkStatus: NetworkReachabilityStatus = .reachable(.ethernetOrWiFi)
#if os(iOS)
if flags.contains(.isWWAN) { networkStatus = .reachable(.wwan) }
#endif
return networkStatus
}
internal func isNetworkReachable(with flags: SCNetworkReachabilityFlags) -> Bool {
let isReachable = flags.contains(.reachable)
let needsConnection = flags.contains(.connectionRequired)
let canConnectAutomatically = flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic)
let canConnectWithoutUserInteraction = canConnectAutomatically && !flags.contains(.interventionRequired)
return isReachable && ( !needsConnection || canConnectWithoutUserInteraction)
}
}
// MARK: -
extension NetworkReachabilityManager.NetworkReachabilityStatus: Equatable {}
/// Returns whether the two network reachability status values are equal.
///
/// - parameter lhs: The left-hand side value to compare.
/// - parameter rhs: The right-hand side value to compare.
///
/// - returns: `true` if the two values are equal, `false` otherwise.
internal func == (lhs: NetworkReachabilityManager.NetworkReachabilityStatus, rhs: NetworkReachabilityManager.NetworkReachabilityStatus)
-> Bool {
switch (lhs, rhs) {
case (.unknown, .unknown):
return true
case (.notReachable, .notReachable):
return true
case let (.reachable(lhsConnectionType), .reachable(rhsConnectionType)):
return lhsConnectionType == rhsConnectionType
default:
return false
}
}
#endif
| mit |
Mobilette/MobiletteFoundation | MBError/MBErrorTests/MBErrorTests.swift | 1 | 972 | //
// MBErrorTests.swift
// MBErrorTests
//
// Created by Romain ASNAR on 19/11/15.
// Copyright © 2015 Romain ASNAR. All rights reserved.
//
import XCTest
@testable import MBError
class MBErrorTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
googlemaps/maps-sdk-for-ios-samples | GooglePlaces-Swift/GooglePlacesSwiftDemos/Swift/SampleListViewController.swift | 1 | 3819 | // Copyright 2020 Google LLC. All rights reserved.
//
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this
// file except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under
// the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
// ANY KIND, either express or implied. See the License for the specific language governing
// permissions and limitations under the License.
import GooglePlaces
import UIKit
/// The class which displays the list of demos.
class SampleListViewController: UITableViewController {
static let sampleCellIdentifier = "sampleCellIdentifier"
let sampleSections = Samples.allSamples()
let configuration: AutocompleteConfiguration = {
let fields: [GMSPlaceField] = [
.name, .placeID, .plusCode, .coordinate, .openingHours, .phoneNumber, .formattedAddress,
.rating, .userRatingsTotal, .priceLevel, .types, .website, .viewport, .addressComponents,
.photos, .utcOffsetMinutes, .businessStatus, .iconImageURL, .iconBackgroundColor,
]
return AutocompleteConfiguration(
autocompleteFilter: GMSAutocompleteFilter(),
placeFields: GMSPlaceField(rawValue: fields.reduce(0) { $0 | $1.rawValue }))
}()
private lazy var editButton: UIBarButtonItem = {
UIBarButtonItem(
title: "Edit", style: .plain, target: self, action: #selector(showConfiguration))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(
UITableViewCell.self, forCellReuseIdentifier: SampleListViewController.sampleCellIdentifier)
tableView.dataSource = self
tableView.delegate = self
navigationItem.rightBarButtonItem = editButton
}
func sample(at indexPath: IndexPath) -> Sample? {
guard indexPath.section >= 0 && indexPath.section < sampleSections.count else { return nil }
let section = sampleSections[indexPath.section]
guard indexPath.row >= 0 && indexPath.row < section.samples.count else { return nil }
return section.samples[indexPath.row]
}
@objc private func showConfiguration(_sender: UIButton) {
navigationController?.present(
ConfigurationViewController(configuration: configuration), animated: true)
}
// MARK: - Override UITableView
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard section <= sampleSections.count else {
return 0
}
return sampleSections[section].samples.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath)
-> UITableViewCell
{
let cell = tableView.dequeueReusableCell(
withIdentifier: SampleListViewController.sampleCellIdentifier, for: indexPath)
if let sample = sample(at: indexPath) {
cell.textLabel?.text = sample.title
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
return sampleSections.count
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
guard section <= sampleSections.count else {
return nil
}
return sampleSections[section].name
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if let sample = sample(at: indexPath) {
let viewController = sample.viewControllerClass.init()
if let controller = viewController as? AutocompleteBaseViewController {
controller.autocompleteConfiguration = configuration
}
navigationController?.pushViewController(viewController, animated: true)
}
}
}
| apache-2.0 |
HighBrace/SimpleTimeSheet | SimpleTimeSheetTests/SimpleTimeSheetTests.swift | 1 | 1078 | //
// SimpleTimeSheetTests.swift
// SimpleTimeSheetTests
//
// Created by Jonas Sääv on 2015-11-28.
// Copyright © 2015 JS HighBrace. All rights reserved.
//
import XCTest
import Quick
import Nimble
@testable import SimpleTimeSheet
class SimpleTimeSheetTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
expect(false).to(equal(false))
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock {
// Put the code you want to measure the time of here.
}
}
}
| mit |
nanashiki/TokyoTechWifiLogin | Source/ConfirmViewController.swift | 1 | 651 | //
// ConfirmViewController.swift
// TokyoTechLogin
//
// Created by nana_dotApp on 2017/05/21.
// Copyright © 2017年 nanashiki. All rights reserved.
//
import Cocoa
class ConfirmViewController: NSViewController {
var message = ""
var success = false
var parentVC = NSViewController()
@IBOutlet weak var messageLabel: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
messageLabel.stringValue = message
}
@IBAction func confirmBtnAction(_ sender: NSButton) {
if success{
parentVC.dismiss(nil)
}else{
self.dismiss(nil)
}
}
}
| mit |
bannzai/ResourceKit | Sources/ResourceKitCore/Parser/XibParser.swift | 1 | 2407 | //
// XibParser.swift
// ResourceKit
//
// Created by kingkong999yhirose on 2016/05/03.
// Copyright © 2016年 kingkong999yhirose. All rights reserved.
//
import Foundation
public protocol XibParser: Parsable {
}
public class XibPerserImpl: NSObject, XibParser {
let url: URL
let resource: AppendableForXibs
fileprivate var name: String = ""
// should parse for root view
// ResourceKit not support second xib view
fileprivate var isOnce: Bool = false
fileprivate let ignoreCase = [
"UIResponder"
]
public init(url: URL, writeResource resource: AppendableForXibs) throws {
self.url = url
self.resource = resource
super.init()
}
public func parse() throws {
guard url.pathExtension == "xib" else {
throw ResourceKitErrorType.spcifiedPathError(path: url.absoluteString, errorInfo: ResourceKitErrorType.createErrorInfo())
}
name = url.deletingPathExtension().lastPathComponent
// Don't create ipad resources
if name.contains("~") {
return
}
guard let parser = XMLParser(contentsOf: url) else {
throw ResourceKitErrorType.spcifiedPathError(path: url.absoluteString, errorInfo: ResourceKitErrorType.createErrorInfo())
}
parser.delegate = self
parser.parse()
}
public func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
generateXibs(attributeDict, elementName: elementName)
}
fileprivate func generateXibs(_ attributes: [String: String], elementName: String) {
if isOnce {
return
}
guard let className = attributes["customClass"] else {
return
}
if ignoreCase.contains(className) {
return
}
let hasFilesOwner = attributes.flatMap ({ $1 }).contains("IBFilesOwner")
if hasFilesOwner {
return
}
isOnce = true
resource
.appendXib(
Xib(
nibName: name,
className: className,
isFilesOwner: hasFilesOwner
)
)
}
}
| mit |
ello/ello-ios | Specs/Networking/ResponseConfigSpec.swift | 1 | 2134 | ////
/// ResponseConfigSpec.swift
//
@testable import Ello
import Quick
import Nimble
class ResponseConfigSpec: QuickSpec {
override func spec() {
describe("ResponseConfig") {
let nextComponents = URLComponents(string: "https://ello.co?next=next")!
let emptyComponents = URLComponents()
context("when the number of remaining pages is 0") {
it("returns true") {
let config = ResponseConfig()
config.totalPagesRemaining = "0"
config.nextQuery = nextComponents
expect(config.isOutOfData()).to(beTrue())
}
}
context("when the number of remaining pages is nil") {
it("returns true") {
let config = ResponseConfig()
config.totalPagesRemaining = .none
config.nextQuery = nextComponents
expect(config.isOutOfData()).to(beTrue())
}
}
context("when the next query items are empty") {
it("returns true") {
let config = ResponseConfig()
config.totalPagesRemaining = "1"
config.nextQuery = emptyComponents
expect(config.isOutOfData()).to(beTrue())
}
}
context("when the next query items are nil") {
it("returns true") {
let config = ResponseConfig()
config.totalPagesRemaining = "1"
config.nextQuery = .none
expect(config.isOutOfData()).to(beTrue())
}
}
context("when the configuration has query items as well as remaining pages") {
it("returns false") {
let config = ResponseConfig()
config.totalPagesRemaining = "1"
config.nextQuery = nextComponents
expect(config.isOutOfData()).to(beFalse())
}
}
}
}
}
| mit |
huangboju/Moots | Examples/SwiftUI/SwiftUI-Kit-master/Shared/SwiftUI_KitApp.swift | 1 | 440 | //
// SwiftUI_KitApp.swift
// SwiftUI Kit
//
// Created by Jordan Singer on 7/10/20.
//
import SwiftUI
@main
struct SwiftUI_KitApp: App {
var body: some Scene {
WindowGroup {
#if os(macOS)
ContentView().frame(minWidth: 100, idealWidth: 300, maxWidth: .infinity, minHeight: 100, idealHeight: 200, maxHeight: .infinity)
#else
ContentView()
#endif
}
}
}
| mit |
arthurhammer/Rulers | Rulers/Model/Preset.swift | 1 | 617 | import Foundation
struct Preset {
var id: String
var name = NSLocalizedString("New Preset", comment: "Name of new preset")
var config = WindowConfig()
init(id: String = NSUUID().uuidString,
name: String = NSLocalizedString("New Preset", comment: "Name of new preset"),
config: WindowConfig = WindowConfig()) {
self.id = id
self.name = name
self.config = config
}
}
extension Preset: Equatable {
static func == (lhs: Preset, rhs: Preset) -> Bool {
return (lhs.id == rhs.id) && (lhs.name == rhs.name) && (lhs.config == rhs.config)
}
}
| mit |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1467-swift-inouttype-get.swift | 12 | 287 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class c {
a<S {
}
let t: SequenceType where I.R
protocol d : a {
func a
| apache-2.0 |
cnoon/swift-compiler-crashes | crashes-duplicates/24070-swift-constraints-constraintgraph-addconstraint.swift | 9 | 255 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c{
var _=a
func a
class A{
class A{
struct B{
protocol A{
func a typealias b:a
| mit |
admkopec/BetaOS | Kernel/Modules/ACPI/AML/Method.swift | 1 | 3381 | //
// Method.swift
// Kernel
//
// Created by Adam Kopeć on 1/26/18.
// Copyright © 2018 Adam Kopeć. All rights reserved.
//
// ACPI Method Invocation
extension ACPI {
struct AMLExecutionContext {
let scope: AMLNameString
let args: AMLTermArgList
let globalObjects: ACPI.GlobalObjects
var endOfMethod = false
private var _returnValue: AMLTermArg? = nil
var returnValue: AMLTermArg? {
mutating get {
let ret = _returnValue
_returnValue = nil
return ret
}
set {
_returnValue = newValue
}
}
var localObjects: [AMLTermArg?] = Array(repeatElement(nil, count: 8))
init(scope: AMLNameString, args: AMLTermArgList, globalObjects: ACPI.GlobalObjects) {
self.scope = scope
self.args = args
self.globalObjects = globalObjects
}
func withNewScope(_ newScope: AMLNameString) -> AMLExecutionContext {
return AMLExecutionContext(scope: newScope, args: [], globalObjects: globalObjects)
}
mutating func execute(termList: AMLTermList) throws {
for termObj in termList {
if let op = termObj as? AMLType2Opcode {
// FIXME, should something be done with the result or maybe it should
// only be returned in the context
_ = try op.execute(context: &self)
} else if let op = termObj as? AMLType1Opcode {
try op.execute(context: &self)
} else if let op = termObj as? AMLNamedObj {
try op.createNamedObject(context: &self)
} else if let op = termObj as? AMLNameSpaceModifierObj {
try op.execute(context: &self)
} else {
fatalError("Unknown op: \(type(of: termObj))")
}
if endOfMethod {
return
}
}
}
}
func invokeMethod(name: String, _ args: Any...) throws -> AMLTermArg? {
var methodArgs: AMLTermArgList = []
for arg in args {
if let arg = arg as? String {
methodArgs.append(AMLString(arg))
} else if let arg = arg as? AMLInteger {
methodArgs.append(AMLIntegerData(AMLInteger(arg)))
} else {
throw AMLError.invalidData(reason: "Bad data: \(arg)")
}
}
guard let mi = /*try*/ AMLMethodInvocation(method: AMLNameString(name), args: methodArgs) else { return nil }
var context = AMLExecutionContext(scope: mi.method, args: [], globalObjects: globalObjects)
return try mi.execute(context: &context)
}
static func _OSI_Method(_ args: AMLTermArgList) throws -> AMLTermArg {
guard args.count == 1 else {
throw AMLError.invalidData(reason: "_OSI: Should only be 1 arg")
}
guard let arg = args[0] as? AMLString else {
throw AMLError.invalidData(reason: "_OSI: is not a string")
}
if arg.value == "Darwin" {
return AMLIntegerData(0xffffffff)
} else {
return AMLIntegerData(0)
}
}
}
| apache-2.0 |
lp1994428/TextKitch | TextKitchen/TextKitchen/classes/Common/KtcDown.swift | 1 | 1035 | //
// KtcDown.swift
// TextKitchen
//
// Created by 罗平 on 2016/10/24.
// Copyright © 2016年 罗平. All rights reserved.
//
import UIKit
import Alamofire
protocol KctDownDelegate:NSObjectProtocol {
// 下载失败
func downloader(downloader:KtcDown,didFailWithError error:NSError)
//下载成功
func downloader(downloader:KtcDown,didFinishWithData data:NSData?)
}
class KtcDown: NSObject {
weak var delegate :KctDownDelegate?
func postWothUrl(urlString:String,params:[String:AnyObject]) {
Alamofire.request(.POST, urlString, parameters: params, encoding: ParameterEncoding.URL, headers: nil).responseData {
(response) in
switch response.result{
case.Failure(let error):
self.delegate?.downloader(self, didFailWithError: error)
case.Success:
self.delegate?.downloader(self, didFinishWithData: response.data)
}
}
}
} | mit |
barteljan/VISPER | VISPER-Core/Classes/TopControllerResolver.swift | 1 | 300 | //
// TopControllerResolver.swift
// VISPER-Wireframe
//
// Created by bartel on 26.12.17.
//
import Foundation
public protocol TopControllerResolver {
func isResponsible(controller: UIViewController) -> Bool
func topController(of controller: UIViewController) -> UIViewController
}
| mit |
CPRTeam/CCIP-iOS | Pods/FSPagerView/Sources/FSPageViewTransformer.swift | 1 | 11428 | //
// FSPagerViewTransformer.swift
// FSPagerView
//
// Created by Wenchao Ding on 05/01/2017.
// Copyright © 2017 Wenchao Ding. All rights reserved.
//
import UIKit
@objc
public enum FSPagerViewTransformerType: Int {
case crossFading
case zoomOut
case depth
case overlap
case linear
case coverFlow
case ferrisWheel
case invertedFerrisWheel
case cubic
}
open class FSPagerViewTransformer: NSObject {
open internal(set) weak var pagerView: FSPagerView?
open internal(set) var type: FSPagerViewTransformerType
open var minimumScale: CGFloat = 0.65
open var minimumAlpha: CGFloat = 0.6
@objc
public init(type: FSPagerViewTransformerType) {
self.type = type
switch type {
case .zoomOut:
self.minimumScale = 0.85
case .depth:
self.minimumScale = 0.5
default:
break
}
}
// Apply transform to attributes - zIndex: Int, frame: CGRect, alpha: CGFloat, transform: CGAffineTransform or transform3D: CATransform3D.
open func applyTransform(to attributes: FSPagerViewLayoutAttributes) {
guard let pagerView = self.pagerView else {
return
}
let position = attributes.position
let scrollDirection = pagerView.scrollDirection
let itemSpacing = (scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height) + self.proposedInteritemSpacing()
switch self.type {
case .crossFading:
var zIndex = 0
var alpha: CGFloat = 0
var transform = CGAffineTransform.identity
switch scrollDirection {
case .horizontal:
transform.tx = -itemSpacing * position
case .vertical:
transform.ty = -itemSpacing * position
}
if (abs(position) < 1) { // [-1,1]
// Use the default slide transition when moving to the left page
alpha = 1 - abs(position)
zIndex = 1
} else { // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0
zIndex = Int.min
}
attributes.alpha = alpha
attributes.transform = transform
attributes.zIndex = zIndex
case .zoomOut:
var alpha: CGFloat = 0
var transform = CGAffineTransform.identity
switch position {
case -CGFloat.greatestFiniteMagnitude ..< -1 : // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0
case -1 ... 1 : // [-1,1]
// Modify the default slide transition to shrink the page as well
let scaleFactor = max(self.minimumScale, 1 - abs(position))
transform.a = scaleFactor
transform.d = scaleFactor
switch scrollDirection {
case .horizontal:
let vertMargin = attributes.bounds.height * (1 - scaleFactor) / 2;
let horzMargin = itemSpacing * (1 - scaleFactor) / 2;
transform.tx = position < 0 ? (horzMargin - vertMargin*2) : (-horzMargin + vertMargin*2)
case .vertical:
let horzMargin = attributes.bounds.width * (1 - scaleFactor) / 2;
let vertMargin = itemSpacing * (1 - scaleFactor) / 2;
transform.ty = position < 0 ? (vertMargin - horzMargin*2) : (-vertMargin + horzMargin*2)
}
// Fade the page relative to its size.
alpha = self.minimumAlpha + (scaleFactor-self.minimumScale)/(1-self.minimumScale)*(1-self.minimumAlpha)
case 1 ... CGFloat.greatestFiniteMagnitude : // (1,+Infinity]
// This page is way off-screen to the right.
alpha = 0
default:
break
}
attributes.alpha = alpha
attributes.transform = transform
case .depth:
var transform = CGAffineTransform.identity
var zIndex = 0
var alpha: CGFloat = 0.0
switch position {
case -CGFloat.greatestFiniteMagnitude ..< -1: // [-Infinity,-1)
// This page is way off-screen to the left.
alpha = 0
zIndex = 0
case -1 ... 0: // [-1,0]
// Use the default slide transition when moving to the left page
alpha = 1
transform.tx = 0
transform.a = 1
transform.d = 1
zIndex = 1
case 0 ..< 1: // (0,1)
// Fade the page out.
alpha = CGFloat(1.0) - position
// Counteract the default slide transition
switch scrollDirection {
case .horizontal:
transform.tx = itemSpacing * -position
case .vertical:
transform.ty = itemSpacing * -position
}
// Scale the page down (between minimumScale and 1)
let scaleFactor = self.minimumScale
+ (1.0 - self.minimumScale) * (1.0 - abs(position));
transform.a = scaleFactor
transform.d = scaleFactor
zIndex = 0
case 1 ... CGFloat.greatestFiniteMagnitude: // [1,+Infinity)
// This page is way off-screen to the right.
alpha = 0
zIndex = 0
default:
break
}
attributes.alpha = alpha
attributes.transform = transform
attributes.zIndex = zIndex
case .overlap,.linear:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
let scale = max(1 - (1-self.minimumScale) * abs(position), self.minimumScale)
let transform = CGAffineTransform(scaleX: scale, y: scale)
attributes.transform = transform
let alpha = (self.minimumAlpha + (1-abs(position))*(1-self.minimumAlpha))
attributes.alpha = alpha
let zIndex = (1-abs(position)) * 10
attributes.zIndex = Int(zIndex)
case .coverFlow:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
let position = min(max(-position,-1) ,1)
let rotation = sin(position*(.pi)*0.5)*(.pi)*0.25*1.5
let translationZ = -itemSpacing * 0.5 * abs(position)
var transform3D = CATransform3DIdentity
transform3D.m34 = -0.002
transform3D = CATransform3DRotate(transform3D, rotation, 0, 1, 0)
transform3D = CATransform3DTranslate(transform3D, 0, 0, translationZ)
attributes.zIndex = 100 - Int(abs(position))
attributes.transform3D = transform3D
case .ferrisWheel, .invertedFerrisWheel:
guard scrollDirection == .horizontal else {
// This type doesn't support vertical mode
return
}
// http://ronnqvi.st/translate-rotate-translate/
var zIndex = 0
var transform = CGAffineTransform.identity
switch position {
case -5 ... 5:
let itemSpacing = attributes.bounds.width+self.proposedInteritemSpacing()
let count: CGFloat = 14
let circle: CGFloat = .pi * 2.0
let radius = itemSpacing * count / circle
let ty = radius * (self.type == .ferrisWheel ? 1 : -1)
let theta = circle / count
let rotation = position * theta * (self.type == .ferrisWheel ? 1 : -1)
transform = transform.translatedBy(x: -position*itemSpacing, y: ty)
transform = transform.rotated(by: rotation)
transform = transform.translatedBy(x: 0, y: -ty)
zIndex = Int((4.0-abs(position)*10))
default:
break
}
attributes.alpha = abs(position) < 0.5 ? 1 : self.minimumAlpha
attributes.transform = transform
attributes.zIndex = zIndex
case .cubic:
switch position {
case -CGFloat.greatestFiniteMagnitude ... -1:
attributes.alpha = 0
case -1 ..< 1:
attributes.alpha = 1
attributes.zIndex = Int((1-position) * CGFloat(10))
let direction: CGFloat = position < 0 ? 1 : -1
let theta = position * .pi * 0.5 * (scrollDirection == .horizontal ? 1 : -1)
let radius = scrollDirection == .horizontal ? attributes.bounds.width : attributes.bounds.height
var transform3D = CATransform3DIdentity
transform3D.m34 = -0.002
switch scrollDirection {
case .horizontal:
// ForwardX -> RotateY -> BackwardX
attributes.center.x += direction*radius*0.5 // ForwardX
transform3D = CATransform3DRotate(transform3D, theta, 0, 1, 0) // RotateY
transform3D = CATransform3DTranslate(transform3D,-direction*radius*0.5, 0, 0) // BackwardX
case .vertical:
// ForwardY -> RotateX -> BackwardY
attributes.center.y += direction*radius*0.5 // ForwardY
transform3D = CATransform3DRotate(transform3D, theta, 1, 0, 0) // RotateX
transform3D = CATransform3DTranslate(transform3D,0, -direction*radius*0.5, 0) // BackwardY
}
attributes.transform3D = transform3D
case 1 ... CGFloat.greatestFiniteMagnitude:
attributes.alpha = 0
default:
attributes.alpha = 0
attributes.zIndex = 0
}
}
}
// An interitem spacing proposed by transformer class. This will override the default interitemSpacing provided by the pager view.
open func proposedInteritemSpacing() -> CGFloat {
guard let pagerView = self.pagerView else {
return 0
}
let scrollDirection = pagerView.scrollDirection
switch self.type {
case .overlap:
guard scrollDirection == .horizontal else {
return 0
}
return pagerView.itemSize.width * -self.minimumScale * 0.6
case .linear:
guard scrollDirection == .horizontal else {
return 0
}
return pagerView.itemSize.width * -self.minimumScale * 0.2
case .coverFlow:
guard scrollDirection == .horizontal else {
return 0
}
return -pagerView.itemSize.width * sin(.pi*0.25*0.25*3.0)
case .ferrisWheel,.invertedFerrisWheel:
guard scrollDirection == .horizontal else {
return 0
}
return -pagerView.itemSize.width * 0.15
case .cubic:
return 0
default:
break
}
return pagerView.interitemSpacing
}
}
| gpl-3.0 |
mikaelbo/MBFacebookImagePicker | MBFacebookImagePicker/Views/MBFacebookPickerEmptyView.swift | 1 | 1322 | //
// MBFacebookPickerEmptyView.swift
// FacebookImagePicker
//
// Copyright © 2017 Mikaelbo. All rights reserved.
//
import UIKit
class MBFacebookPickerEmptyView: UIView {
let titleLabel = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
configureLabel()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
configureLabel()
}
fileprivate func configureLabel() {
titleLabel.numberOfLines = 2
let wantedSize = CGSize(width: 205, height: 40)
titleLabel.textAlignment = .center
titleLabel.frame = CGRect(x: (bounds.size.width - wantedSize.width) / 2,
y: (bounds.size.height - wantedSize.height) / 2,
width: wantedSize.width,
height: wantedSize.height)
titleLabel.font = UIFont.systemFont(ofSize: 15)
titleLabel.textColor = UIColor(red: 85 / 255, green: 85 / 255, blue: 85 / 255, alpha: 0.5)
titleLabel.autoresizingMask = [.flexibleTopMargin,
.flexibleBottomMargin,
.flexibleLeftMargin,
.flexibleRightMargin]
addSubview(titleLabel)
}
}
| mit |
HabitRPG/habitrpg-ios | HabiticaTests/UI/Tasks/TaskDetailLineViewTests.swift | 1 | 6537 | //
// TaskDetailLineViewTests.swift
// Habitica
//
// Created by Phillip Thelen on 19/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import XCTest
@testable import Habitica
import Habitica_Models
import Nimble
class TaskDetailLineViewTests: HabiticaTests {
let taskDetailLine = TaskDetailLineView(frame: CGRect(x: 0, y: 0, width: 350, height: 21))
var task = TestTask()
override func setUp() {
super.setUp()
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
taskDetailLine.dateFormatter = dateFormatter
self.task = TestTask()
task.text = "Task Title"
task.notes = "Task notes"
task.type = "habit"
self.recordMode = true
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testDefaultEmpty() {
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
expect(self.taskDetailLine.hasContent) == false
}
func testTagsVisible() {
task.tags = [MockTag()]
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == false
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
}
func testChallengeVisible() {
task.challengeID = "challengeId"
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == false
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
}
func testReminderVisible() {
task.reminders = [MockReminder()]
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == false
expect(self.taskDetailLine.streakIconView.isHidden) == true
}
func testStreakVisible() {
task.streak = 2
task.type = "daily"
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == false
expect(self.taskDetailLine.streakLabel.text) == "2"
}
func testStreakHiddenIfZero() {
task.streak = 0
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
}
func testTodoDueToday() {
task.duedate = Date()
task.type = "todo"
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
expect(self.taskDetailLine.calendarIconView.isHidden) == false
expect(self.taskDetailLine.detailLabel.text) == "Due today"
}
func testTodoDueTomorrow() {
task.duedate = Calendar.current.date(byAdding: .day, value: 1, to: Date())
task.type = "todo"
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
expect(self.taskDetailLine.calendarIconView.isHidden) == false
expect(self.taskDetailLine.detailLabel.text) == "Due tomorrow"
}
func testTodoDueIn3Days() {
task.duedate = Calendar.current.date(byAdding: .day, value: 3, to: Date())
task.type = "todo"
taskDetailLine.configure(task: task)
expect(self.taskDetailLine.challengeIconView.isHidden) == true
expect(self.taskDetailLine.tagIconView.isHidden) == true
expect(self.taskDetailLine.reminderIconView.isHidden) == true
expect(self.taskDetailLine.streakIconView.isHidden) == true
expect(self.taskDetailLine.calendarIconView.isHidden) == false
expect(self.taskDetailLine.detailLabel.text) == "Due in 3 days"
}
}
class TestTask: TaskProtocol {
var isValid: Bool = true
var nextDue: [Date] = []
var weeksOfMonth: [Int] = []
var daysOfMonth: [Int] = []
var isNewTask: Bool = false
var isSynced: Bool = true
var isSyncing: Bool = false
var createdAt: Date?
var updatedAt: Date?
var startDate: Date?
var yesterDaily: Bool = true
var weekRepeat: WeekRepeatProtocol?
var frequency: String?
var everyX: Int = 1
var tags: [TagProtocol] = []
var checklist: [ChecklistItemProtocol] = []
var reminders: [ReminderProtocol] = []
var id: String?
var text: String?
var notes: String?
var type: String?
var value: Float = 0
var attribute: String?
var completed: Bool = false
var down: Bool = false
var up: Bool = false
var order: Int = 0
var priority: Float = 0
var counterUp: Int = 0
var counterDown: Int = 0
var duedate: Date?
var isDue: Bool = false
var streak: Int = 0
var challengeID: String?
}
class MockTag: TagProtocol {
var id: String?
var text: String?
var order: Int = 0
}
class MockReminder: ReminderProtocol {
var id: String?
var startDate: Date?
var time: Date?
var task: TaskProtocol?
}
| gpl-3.0 |
k-o-d-e-n/CGLayout | Sources/Classes/container.cglayout.swift | 1 | 4212 | //
// LayoutElementsContainer.swift
// CGLayout
//
// Created by Denis Koryttsev on 01/10/2017.
//
//
#if os(iOS) || os(tvOS)
import UIKit
#elseif os(macOS)
import Cocoa
#elseif os(Linux)
import Foundation
#endif
protocol EnterPoint {
associatedtype Container
var child: LayoutElement { get }
func add(to container: Container)
}
protocol ContainerManagement {
associatedtype Child
associatedtype Container
func add(_ child: Child, to container: Container)
}
struct Enter<Container>: EnterPoint {
let base: _AnyEnterPoint<Container>
var child: LayoutElement { return base.child }
init<Point: EnterPoint>(_ base: Point) where Point.Container == Container {
self.base = _Enter(base)
}
init<Management: ContainerManagement>(_ element: Management.Child, managedBy management: Management) where Management.Child: LayoutElement, Management.Container == Container {
self.base = _Enter(Enter.Any.init(element: element, management: management))
}
func add(to container: Container) {
base.add(to: container)
}
private struct `Any`<Management: ContainerManagement>: EnterPoint where Management.Child: LayoutElement, Management.Container == Container {
let element: Management.Child
let management: Management
var child: LayoutElement { element }
func add(to container: Container) {
management.add(element, to: container)
}
}
}
class _AnyEnterPoint<Container>: EnterPoint {
var child: LayoutElement { fatalError("Unimplemented") }
func add(to container: Container) {
fatalError("Unimplemented")
}
}
final class _Enter<Base: EnterPoint>: _AnyEnterPoint<Base.Container> {
private let base: Base
override var child: LayoutElement { base.child }
init(_ base: Base) {
self.base = base
}
override func add(to container: Base.Container) {
base.add(to: container)
}
}
/// The container does not know which child is being added,
/// but the child knows exactly where it is being added
protocol ChildrenProtocol {
associatedtype Child
func add(_ child: Child)
//func remove(_ child: Child)
}
#if os(iOS)
extension UIView {
struct SublayerManagement<Container: UIView>: ContainerManagement {
func add(_ child: CALayer, to container: Container) {
container.layer.addSublayer(child)
}
}
}
extension CALayer {
struct Layers: ChildrenProtocol {
let layer: CALayer
func add(_ child: CALayer) {
layer.addSublayer(layer)
}
}
}
public extension UIView {
var sublayers: Layers { return Layers(base: CALayer.Layers(layer: layer)) }
struct Layers: ChildrenProtocol {
let base: CALayer.Layers
func add(_ child: CALayer) {
base.add(child)
}
}
var layoutGuides: LayoutGuides { return LayoutGuides(view: self) }
struct LayoutGuides: ChildrenProtocol {
let view: UIView
func add(_ child: LayoutGuide<UIView>) {
child.add(to: view)
}
}
}
public extension StackLayoutGuide where Parent: UIView {
var views: Views { return Views(stackLayoutGuide: self) }
struct Views: ChildrenProtocol {
let stackLayoutGuide: StackLayoutGuide<Parent>
func add(_ child: UIView) {
stackLayoutGuide.ownerElement?.addSubview(child)
stackLayoutGuide.items.append(.uiView(child))
}
}
var layers: Layers { return Layers(stackLayoutGuide: self) }
struct Layers: ChildrenProtocol {
let stackLayoutGuide: StackLayoutGuide<Parent>
func add(_ child: CALayer) {
stackLayoutGuide.ownerElement?.layer.addSublayer(child)
stackLayoutGuide.items.append(.caLayer(child))
}
}
var layoutGuides: LayoutGuides { return LayoutGuides(stackLayoutGuide: self) }
struct LayoutGuides: ChildrenProtocol {
let stackLayoutGuide: StackLayoutGuide<Parent>
func add(_ child: LayoutGuide<UIView>) {
stackLayoutGuide.ownerElement?.add(layoutGuide: child)
stackLayoutGuide.items.append(.layoutGuide(child))
}
}
}
#endif
| mit |
123kyky/SteamReader | SteamReader/SteamReader/View/NewsItemView.swift | 1 | 1201 | //
// NewsItemView.swift
// SteamReader
//
// Created by Kyle Roberts on 4/29/16.
// Copyright © 2016 Kyle Roberts. All rights reserved.
//
import UIKit
class NewsItemView: UIView, UIWebViewDelegate {
@IBOutlet var view: UIView!
@IBOutlet weak var webView: UIWebView!
var newsItem: NewsItem! {
didSet {
if newsItem.contents != nil {
let html = "<html><head><link rel=\"stylesheet\" type=\"text/css\" href=\"news.css\"></head>" + "<body>\(newsItem.contents!)</body></html>"
webView.loadHTMLString(html, baseURL: NSBundle.mainBundle().bundleURL)
}
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSBundle.mainBundle().loadNibNamed("NewsItemView", owner: self, options: nil)
addSubview(view)
view.snp_makeConstraints { (make) in
make.edges.equalTo(self)
}
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
// TODO: Handle news navigation (back button)
return navigationType == .Other
}
}
| mit |
Snowy1803/BreakBaloon-mobile | BreakBaloon/RandGame/RandGameBonusLevel.swift | 1 | 1344 | //
// RandGameBonusLevel.swift
// BreakBaloon
//
// Created by Emil on 02/08/2016.
// Copyright © 2016 Snowy_1803. All rights reserved.
//
import Foundation
import SpriteKit
class RandGameBonusLevel: RandGameLevel {
let modifier: Double
init(_ index: Int, modifier: Double) {
self.modifier = modifier
super.init(index)
}
override func start(_ view: SKView, transition: SKTransition = SKTransition.flipVertical(withDuration: 1)) {
gamescene = RandGameScene(view: view, level: self)
view.presentScene(gamescene!, transition: transition)
gamescene!.addChild(RandGameBonusLevelInfoNode(level: self, scene: gamescene!))
}
override func end(_ missing: Int) {
guard !status.finished else {
super.end(missing)
return
}
let xp = Double(max(0, numberOfBaloons - missing)) * modifier
gamescene!.gvc.addXP(xp)
let stars = missing == 0 ? 3 : missing <= maxMissingBaloonToWin / 2 ? 2 : 1
status = RandGameLevelStatus.getFinished(stars: stars)
unlockNextLevel()
gamescene?.addChild(RandGameLevelEndNode(level: self, scene: gamescene!, stars: stars, xpBonus: Int(xp)))
}
override func createNode() -> RandGameLevelNode {
RandGameBonusLevelNode(level: self)
}
}
| mit |
kstaring/swift | validation-test/compiler_crashers_fixed/00500-llvm-ondiskchainedhashtable-swift-modulefile-decltableinfo-find.swift | 11 | 431 | // 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
class C<T where I.E == F>: AnyObject.h
| apache-2.0 |
merlos/iOS-Open-GPX-Tracker | OpenGpxTracker/DistanceLabel.swift | 1 | 1329 | //
// DistanceLabel.swift
// OpenGpxTracker
//
// Created by merlos on 01/10/15.
//
import Foundation
import UIKit
import MapKit
///
/// A label to display distances.
///
/// The text is displated in meters if is less than 1km (for instance "980m") and in
/// km with two decimals if it is larger than 1km (for instance "1.20km").
///
/// If `useImperial` is true, it displays the distance always in miles ("0.23mi").
///
/// To update the text displayed set the `distance` property.
///
open class DistanceLabel: UILabel {
/// Internal variable that keeps the actual distance
private var _distance = 0.0
///Internal variable to keep the use of imperial units
private var _useImperial = false
/// Use imperial units (miles)? False by default.
/// If true, displays meters and kilometers
open var useImperial: Bool {
get {
return _useImperial
}
set {
_useImperial = newValue
distance = _distance //updates text displayed to reflect the new units
}
}
/// Distance in meters
open var distance: CLLocationDistance {
get {
return _distance
}
set {
_distance = newValue
text = newValue.toDistance(useImperial: _useImperial)
}
}
}
| gpl-3.0 |
trafi/SlideOutable | IB/IBSlideOutable.swift | 1 | 1650 | //
// IBSlideOutable.swift
// Trafi
//
// Created by Domas on 15/12/2016.
// Copyright © 2016 Intelligent Communications. All rights reserved.
//
import SlideOutable
public class IBSlideOutable: SlideOutable {
/**
The top padding that contents will not scroll on.
Animatable.
The default value is `0`.
*/
@IBInspectable dynamic override public var topPadding: CGFloat { didSet {} }
/**
The mid anchor fraction from `0` (the very bottom) to `1` the very top of the `SlideOutable` view bounds. Setting it to `nil` would disable the anchoring.
Animatable.
The default value is `0.4`.
*/
@IBInspectable override public var anchorFraction: CGFloat? { didSet {} }
/**
The minimum content visible content (header and scroll) height.
Animatable.
The default value is header's `bounds.height` or `120` if header is not set.
*/
@IBInspectable dynamic override public var minContentHeight: CGFloat { didSet {} }
/**
Proxy for `minimumContentHeight` without header's `bounds.height`.
Animatable.
*/
@IBInspectable override public var minScrollHeight: CGFloat { didSet {} }
/**
Determens weather the scroll's `bounds.height` can get bigger than it's `contentSize.height`.
Animatable.
The default value is `true`.
*/
@IBInspectable override public var isScrollStretchable: Bool { didSet {} }
@IBOutlet override public var header: UIView? { didSet {} }
@IBOutlet override public var scroll: UIScrollView! { didSet {} }
}
| mit |
davidtps/douyuDemo | douyuDemo/douyuDemo/Classes/Home/Controller/HomeViewController.swift | 1 | 4464 | //
// HomeViewController.swift
// douyuDemo
//
// Created by 田鹏升 on 2017/8/31.
// Copyright © 2017年 田鹏升. All rights reserved.
//
import UIKit
private let mTitleViewH:CGFloat = 40
class HomeViewController: UIViewController {
// MARK:- 懒加载 titleView contentView
fileprivate lazy var pageTitleView:PageTitleView = {[weak self] in //避免循环引用问题
let titleFrame = CGRect(x: 0, y: mStatusBarH+mNavigationBarH, width: mScreenW, height: mTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleview = PageTitleView(frame: titleFrame, titles: titles)
titleview.delegate = self
return titleview
}()
fileprivate lazy var pageContentView:PageContentView = {[unowned self] in
let contentViewH = mScreenH - (mStatusBarH+mNavigationBarH+mTitleViewH+mTabBarH)
let contentFrame = CGRect(x: 0, y: mStatusBarH+mNavigationBarH+mTitleViewH, width: mScreenW, height: contentViewH)
var childVcs:[UIViewController] = [UIViewController]()
childVcs.append(RecommendViewController())
for _ in 0..<3{
let vc = UIViewController()
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parentVc: self)
contentView.delegate = self
return contentView
}()
override func viewDidLoad() {
super.viewDidLoad()
initUI()
}
}
// MARK:- 实现pageTitleVeiw 的代理协议,通知pageContentView 做出切换
extension HomeViewController:PageTitleViewDelegate{
func pageTitleViewClick(selectedIndex index: Int) {
pageContentView.setSelectedPage(index: index)
}
}
// MARK:- 实现pageContentView 的代理协议
extension HomeViewController :PageContentViewDelegate{
func pageScrollEvent(pageContentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleViewChange(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
extension HomeViewController{
fileprivate func initUI(){
//scrollview 不需要内边距
automaticallyAdjustsScrollViewInsets = false
// MARK:- 初始化导航栏UI
navigationInit();
// MARK:- 添加pageTitle
view.addSubview(pageTitleView)
// MARK:- 添加contentView
view.addSubview(pageContentView)
}
func navigationInit() {
// 左侧,设置logo
// let logo = UIButton();
// logo.setImage(UIImage(named:"logo"), for: UIControlState.normal)
// logo.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(normal: "logo")
//设置右侧 item
let size = CGSize(width:40,height:40);
// let hisBtn = UIButton();
//
// hisBtn.setImage(UIImage(named:"image_my_history"), for: UIControlState.normal)
// hisBtn.setImage(UIImage(named:"Image_my_history_click"), for: UIControlState.highlighted)
// hisBtn.frame = CGRect(origin: CGPoint.zero, size: size)
//
// let scanBtn = UIButton();
// scanBtn.setImage(UIImage(named:"Image_scan"), for: UIControlState.normal)
// scanBtn.setImage(UIImage(named:"Image_scan_click"), for: UIControlState.highlighted)
// scanBtn.frame = CGRect(origin: CGPoint.zero, size: size)
//
//
// let searchBtn = UIButton();
// searchBtn.setImage(UIImage(named:"btn_search"), for: UIControlState.normal)
// searchBtn.setImage(UIImage(named:"btn_search_clicked"), for: UIControlState.highlighted)
// searchBtn.frame = CGRect(origin: CGPoint.zero, size: size)
let history = UIBarButtonItem(normal:"image_my_history",highlight:"Image_my_history_click",size:size)
let scan = UIBarButtonItem(normal:"Image_scan",highlight:"Image_scan_click",size:size)
let search = UIBarButtonItem(normal:"btn_search",highlight:"btn_search_clicked",size:size)
navigationItem.rightBarButtonItems = [history,scan,search]
}
}
| apache-2.0 |
tjw/swift | test/IRGen/mangle-anonclosure.swift | 5 | 738 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir %s -o - | %FileCheck %s
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
class HeapStorage<Value, Element> {
public final func withUnsafeMutablePointerToElements<R>(
body: (UnsafeMutablePointer<Element>) -> R
) -> R { return body(someValidPointer()) }
}
struct CountAndCapacity {}
class TestHeapStorage<T> : HeapStorage<CountAndCapacity,T> {
deinit {
withUnsafeMutablePointerToElements {
// Don't crash when mangling this closure's name.
// CHECK: $S4main15TestHeapStorageCfdySpyxGXEfU_
// ---> main.TestHeapStorage.deinit.(closure #1)
(p: UnsafeMutablePointer<T>) -> () in
}
}
}
| apache-2.0 |
davidbjames/Uniview | Pods/Unilib/Unilib/Sources/Strings.swift | 1 | 309 | //
// Strings.swift
// Unilib
//
// Created by David James on 9/28/16.
// Copyright © 2016 David B James. All rights reserved.
//
import Foundation
public extension String {
/// Does the string have length (!empty)
var hasText:Bool {
get {
return !isEmpty
}
}
}
| mit |
loicmonney/iOS-MediaPlayer | MediaPlayer/MediaPlayer/PlayMovieUIController.swift | 1 | 635 | //
// PlayMovieUIController.swift
// MediaPlayer
//
// Created by Loïc Monney on 18/12/15.
// Copyright © 2015 Loïc Monney. All rights reserved.
//
import UIKit
import AVKit
import AVFoundation
class PlayMovieUIController : UIViewController {
@IBAction func playMovieClicked(sender: UIButton) {
let videoURL = NSURL(string: "http://jplayer.org/video/m4v/Big_Buck_Bunny_Trailer.m4v")
let player = AVPlayer(URL: videoURL!)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.frame = self.view.bounds
self.view.layer.addSublayer(playerLayer)
player.play()
}
}
| mit |
kokoroe/kokoroe-sdk-ios | KokoroeSDK/Network/Authentication/KKRAuthenticationRequest.swift | 1 | 3773 | //
// KKRAuthenticationRequest.swift
// KokoroeSDK
//
// Created by Guillaume Mirambeau on 27/04/2016.
// Copyright © 2016 I know u will. All rights reserved.
//
import Foundation
import Alamofire
import AlamofireObjectMapper
import ObjectMapper
enum KKRAuthenticationConstant {
case Unknown, Password, Facebook
func value() -> String {
switch self {
case .Unknown:
return "unknown"
case .Password:
return "password"
case .Facebook:
return "facebook"
}
}
}
enum KKRAuthenticationType {
case None, Email, Facebook
};
class KKRAuthenticationRequestObject: KKRMasterRequestObject {
var email: String? {
didSet {
if let unwrapEmail = email {
self.container["username"] = unwrapEmail
} else {
self.container.removeValueForKey("username")
}
}
}
var password: String? {
didSet {
if let unwrapPassword = password {
self.container["password"] = unwrapPassword
} else {
self.container.removeValueForKey("password")
}
}
}
var token: String? {
didSet {
if let unwrapToken = token {
self.container["token"] = unwrapToken
} else {
self.container.removeValueForKey("token")
}
}
}
private var _grantType: String?
//var connectionType:KKRConnectionType = .None
//private var _authenticationType: KKRAuthenticationType = .None
var authenticationType: KKRAuthenticationType = .None {
didSet {
//_authenticationType = newValue
switch authenticationType {
case .Email:
_grantType = KKRAuthenticationConstant.Password.value()
self.container["grant_type"] = _grantType
case .Facebook:
_grantType = KKRAuthenticationConstant.Facebook.value()
self.container["grant_type"] = _grantType
default:
_grantType = KKRAuthenticationConstant.Unknown.value()
self.container.removeValueForKey("grant_type")
}
}
}
}
let KKRConnectionPathPattern = "/oauth/token"
class KKRAuthenticationRequest: NSObject {
func authentication(authenticationObject: KKRAuthenticationRequestObject, completion: (result: KKRAuthenticationResponseObject?, error: NSError?) -> Void) {
KKRMasterRequest.sharedInstance.request(.POST, KKRConnectionPathPattern, bodyParameters: authenticationObject.container)
.validate()
.responseObject { (response: Response<KKRAuthenticationResponseObject, NSError>) in
switch response.result {
case .Success:
if let authenticationResponseObject = response.result.value {
completion(result: authenticationResponseObject, error: nil)
} else {
completion(result: nil, error: nil)
}
case .Failure(let error):
completion(result: nil, error: error)
}
}
}
func logout() {
KKRMasterRequest.sharedInstance.accessToken = nil
}
}
class KKRAuthenticationResponseObject: Mappable {
var accessToken: String?
var tokenType: String?
var expiresIn: Int?
required init?(_ map: Map){
}
func mapping(map: Map) {
self.accessToken <- map["access_token"]
self.tokenType <- map["token_type"]
self.expiresIn <- map["expires_in"]
}
} | mit |
caffeinelabs/channel.build | src/channel.build.tvos/channel/Config.swift | 1 | 2013 | //
// Config.swift
// channel
//
// Created by Michael Kalygin on 15/02/16.
// Copyright © 2016 caffeinelabs. All rights reserved.
//
import UIKit
// Helper structure to store app settings extracted from Info.plist.
// NOTE: Some of the settings are different for different Xcode build schemes.
struct Config {
static let deviceID = UIDevice.currentDevice().identifierForVendor!.UUIDString
static let channelName = Config.getKey("CFBundleName") as! String
static let channelID = Config.getKey("Channel ID") as! String
static let TVJSClientVersion = Config.getClientVersion()
static let TVJSClientURL = Config.getKeyWithSub("TVJS Client URL", target: "%N", sub: TVJSClientVersion)
static let TVJSAppURL = Config.getKeyWithSub("TVJS App URL", target: "%N", sub: TVJSClientVersion)
static let webAPIURL = Config.getKey("Web API URL") as! String
private static func getKey(key: String) -> AnyObject? {
return NSBundle.mainBundle().objectForInfoDictionaryKey(key)
}
private static func getClientVersion() -> String {
let getChannelsURL = "\(Config.webAPIURL)admin"
let semaphore = dispatch_semaphore_create(0)
var version = "1"
HTTP.get(getChannelsURL) { data, error in
guard let channels = data as? [[String: AnyObject]],
i = channels.indexOf({ $0["_id"] as? String == Config.channelID }),
clientVersion = channels[i]["clientVersion"] as? String else {
print("Unable to retrieve version from \(getChannelsURL)")
dispatch_semaphore_signal(semaphore)
return
}
version = clientVersion
dispatch_semaphore_signal(semaphore)
}
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return version
}
private static func getKeyWithSub(key: String, target: String, sub: String) -> String {
let prop = Config.getKey(key) as! String
return prop.stringByReplacingOccurrencesOfString(target, withString: sub)
}
} | agpl-3.0 |
SanctionCo/pilot-ios | pilot/PilotConfiguration.swift | 1 | 1199 | //
// PilotConfiguration.swift
// pilot
//
// Created by Nick Eckert on 7/25/17.
// Copyright © 2017 sanction. All rights reserved.
//
import Foundation
struct PilotConfiguration {
struct Thunder {
static let host = "http://thunder.sanctionco.com"
static let userKey = "lightning"
static let userSecret = "secret"
static let basicCredentials = "\(userKey):\(userSecret)"
.data(using: String.Encoding.utf8)!.base64EncodedString(options: [])
}
struct Lightning {
static let host = "http://lightning.sanctionco.com"
static let userKey = "application"
static let userSecret = "secret"
static let basicCredentials = "\(userKey):\(userSecret)"
.data(using: String.Encoding.utf8)!.base64EncodedString(options: [])
// Facebook
static let facebookRedirectURL = "fb896501930437172://authorize"
static let facebookRedirectScheme = "fb896501930437172"
static let facebookTokenParamKey = "access_token"
// Twitter
static let twitterRedirectURL = "pilot://twitter"
static let twitterRedirectScheme = "pilot"
static let twitterTokenParamKey = "oauth_token"
static let twitterVerifierParamKey = "oauth_verifier"
}
}
| mit |
WangWenzhuang/ZKProgressHUD | ZKProgressHUD/ZKProgressView.swift | 1 | 1972 | //
// ZKProgressView.swift
// ZKProgressHUD
//
// Created by 王文壮 on 2017/3/15.
// Copyright © 2017年 WangWenzhuang. All rights reserved.
//
import UIKit
/// 进度
class ZKProgressView: UIView {
var progressColor: UIColor?
var progressFont: UIFont?
private var _progress: Double = 0
private var textLabel: UILabel!
var progress: Double {
get {
return _progress
}
set {
self._progress = newValue
self.setNeedsDisplay()
self.setNeedsLayout()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.textLabel = UILabel()
self.addSubview(self.textLabel)
self.textLabel.textAlignment = .center
self.textLabel.font = self.progressFont ?? Config.font
self.textLabel.textColor = self.progressColor ?? Config.foregroundColor
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.textLabel.text = "\(Int(self.progress * 100))%"
self.textLabel.sizeToFit()
self.textLabel.frame.origin = CGPoint(x: (self.width - self.textLabel.width) / 2, y: (self.height - self.textLabel.height) / 2)
}
override func draw(_ rect: CGRect) {
if let ctx = UIGraphicsGetCurrentContext() {
let arcCenter = CGPoint(x: self.width / 2, y: self.width / 2)
let radius = arcCenter.x - 2
let startAngle = -(Double.pi / 2)
let endAngle = startAngle + Double.pi * 2 * self.progress
let path = UIBezierPath(arcCenter: arcCenter, radius: radius, startAngle: CGFloat(startAngle), endAngle: CGFloat(endAngle), clockwise: true)
ctx.setLineWidth(4)
self.progressColor?.setStroke()
ctx.addPath(path.cgPath)
ctx.strokePath()
}
}
}
| mit |
robin/YLUtils | MyPlayground.playground/Sources/PlaygroundUtils.swift | 1 | 632 | import Foundation
import UIKit
public func viewWithLayer(layer: CALayer, size: CGSize = CGSize(width: 300, height: 300)) -> UIView {
let view = UIView(frame: CGRect(origin: .zero, size: size))
layer.bounds = view.bounds
layer.position = view.center
view.layer.addSublayer(layer)
return view
}
public func viewWithPath(path: UIBezierPath, size: CGSize = CGSize(width: 300, height: 300)) -> UIView {
let layer = CAShapeLayer()
layer.strokeColor = UIColor.whiteColor().CGColor
layer.path = path.CGPath
layer.fillColor = UIColor.darkGrayColor().CGColor
return viewWithLayer(layer, size: size)
} | mit |
lionchina/RxSwiftBook | RxTableView/RxTableViewTests/RxTableViewTests.swift | 1 | 989 | //
// RxTableViewTests.swift
// RxTableViewTests
//
// Created by MaxChen on 04/08/2017.
// Copyright © 2017 com.linglustudio. All rights reserved.
//
import XCTest
@testable import RxTableView
class RxTableViewTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| apache-2.0 |
kumabook/FeedlyKit | Spec/EntrySpec.swift | 1 | 1692 | //
// EntrySpec.swift
// FeedlyKit
//
// Created by Hiroki Kumamoto on 1/18/15.
// Copyright (c) 2015 Hiroki Kumamoto. All rights reserved.
//
import FeedlyKit
import Quick
import Nimble
import SwiftyJSON
class EntrySpec: QuickSpec {
override func spec() {
describe("a entry") {
it ("should be constructed with json") {
let json = JSON(SpecHelper.fixtureJSONObject(fixtureNamed: "entry")!)
let entry: Entry = Entry(json: json)
expect(entry).notTo(beNil())
expect(entry.id).notTo(beNil())
expect(entry.title).notTo(beNil())
expect(entry.content).notTo(beNil())
expect(entry.summary).to(beNil())
expect(entry.author).notTo(beNil())
expect(entry.crawled).notTo(beNil())
expect(entry.recrawled).notTo(beNil())
expect(entry.published).notTo(beNil())
expect(entry.updated).notTo(beNil())
expect(entry.alternate).notTo(beNil())
expect(entry.origin).notTo(beNil())
expect(entry.keywords).notTo(beNil())
expect(entry.visual).notTo(beNil())
expect(entry.unread).notTo(beNil())
expect(entry.categories).notTo(beNil())
expect(entry.engagement).notTo(beNil())
expect(entry.actionTimestamp).to(beNil())
expect(entry.enclosure).to(beNil())
expect(entry.fingerprint).to(beNil())
expect(entry.originId).to(beNil())
expect(entry.sid).to(beNil())
}
}
}
}
| mit |
HTWDD/HTWDresden-iOS | HTWDD/Core/Network/HTWRestApi.swift | 1 | 3320 | //
// RestApi.swift
// HTWDD
//
// Created by Mustafa Karademir on 30.06.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import Foundation
import Moya
// MARK: - Endpoints
enum HTWRestApi {
case timeTable(year: String, major: String, group: String)
case electiveLessons
case semesterPlaning
case rooms(room: String)
case studyGroups
case courses(auth: String)
case grades(auth: String, examinationRegulations: Int, majorNumber: String, graduationNumber: String)
case exams(year: String, major: String, group: String, grade: String)
}
// MARK: - Endpoint Handling
extension HTWRestApi: TargetType {
var baseURL: URL {
switch self {
case .courses,
.grades:
return URL(string: "https://wwwqis.htw-dresden.de/appservice/v2")!
case .exams:
return URL(string: "http://www2.htw-dresden.de/~app/API")!
default:
return URL(string: "https://rubu2.rz.htw-dresden.de/API/v0")!
}
}
var path: String {
switch self {
case .timeTable: return "/studentTimetable.php"
case .electiveLessons: return "/studentTimetable.php"
case .semesterPlaning: return "/semesterplan.json"
case .rooms: return "/roomTimetable.php"
case .studyGroups: return "/studyGroups.php"
case .courses: return "/getcourses"
case .grades: return "/getgrades"
case .exams: return "/GetExams.php"
}
}
var method: Moya.Method {
return .get
}
var sampleData: Data {
return Data()
}
var task: Task {
switch self {
case .timeTable(let year, let major, let group):
return .requestParameters(parameters: [ "Stg": "\(major.urlEscaped)", "StgGrp": "\(group.urlEscaped)", "StgJhr": "\(year.urlEscaped)" ], encoding: URLEncoding.default)
case .rooms(let room):
return .requestParameters(parameters: ["room": room], encoding: URLEncoding.default)
case .exams(let year, let major, let group, let grade):
return .requestParameters(parameters: ["Stg": "\(major.urlEscaped)", "StgNr": "\(group.urlEscaped)", "StgJhr": "\(year.urlEscaped)", "AbSc": "\(grade.urlEscaped)"], encoding: URLEncoding.default)
case .grades(_, let examinationRegulations, let majorNumber, let graduationNumber):
return .requestParameters(parameters: ["POVersion" : "\(examinationRegulations)", "StgNr": majorNumber, "AbschlNr": graduationNumber], encoding: URLEncoding.default)
case .electiveLessons:
return .requestParameters(parameters: ["all" : "true"], encoding: URLEncoding.default)
default:
return .requestPlain
}
}
var headers: [String : String]? {
switch self {
case .courses(let auth):
return ["Content-Type": "application/json", "Authorization": "Basic \(auth)"]
case .grades(let auth, _, _, _):
return ["Content-Type": "application/json", "Authorization": "Basic \(auth)"]
default:
return ["Content-Type": "application/json"]
}
}
}
extension HTWRestApi: CachePolicyGettable {
var cachePolicy: URLRequest.CachePolicy {
return .reloadRevalidatingCacheData
}
}
| gpl-2.0 |
mattrubin/SwiftGit2 | SwiftGit2/Errors.swift | 1 | 1808 | import Foundation
import libgit2
public let libGit2ErrorDomain = "org.libgit2.libgit2"
internal extension NSError {
/// Returns an NSError with an error domain and message for libgit2 errors.
///
/// :param: errorCode An error code returned by a libgit2 function.
/// :param: libGit2PointOfFailure The name of the libgit2 function that produced the
/// error code.
/// :returns: An NSError with a libgit2 error domain, code, and message.
convenience init(gitError errorCode: Int32, pointOfFailure: String? = nil) {
let code = Int(errorCode)
var userInfo: [String: String] = [:]
if let message = errorMessage(errorCode) {
userInfo[NSLocalizedDescriptionKey] = message
} else {
userInfo[NSLocalizedDescriptionKey] = "Unknown libgit2 error."
}
if let pointOfFailure = pointOfFailure {
userInfo[NSLocalizedFailureReasonErrorKey] = "\(pointOfFailure) failed."
}
self.init(domain: libGit2ErrorDomain, code: code, userInfo: userInfo)
}
}
/// Returns the libgit2 error message for the given error code.
///
/// The error message represents the last error message generated by
/// libgit2 in the current thread.
///
/// :param: errorCode An error code returned by a libgit2 function.
/// :returns: If the error message exists either in libgit2's thread-specific registry,
/// or errno has been set by the system, this function returns the
/// corresponding string representation of that error. Otherwise, it returns
/// nil.
private func errorMessage(_ errorCode: Int32) -> String? {
let last = giterr_last()
if let lastErrorPointer = last {
return String(validatingUTF8: lastErrorPointer.pointee.message)
} else if UInt32(errorCode) == GITERR_OS.rawValue {
return String(validatingUTF8: strerror(errno))
} else {
return nil
}
}
| mit |
sacrelee/iOSDev | Notes/Swift/Coding.playground/Pages/Classes and Structures.xcplaygroundpage/Contents.swift | 1 | 3098 | /// 类和结构体
// swift中类和结构体的关系更加密切,以下主要通过实例而不是对象来说明
/* 类与结构体的相同点:
*定义属性用于存储值
*定义方法用于提供功能
*定义附属脚本用于访问值
*定义构造器用于生成初始化值
*通过扩展以增加默认实现的功能
*实现协议以提供某种标准功能”
类另外拥有以下附加功能:
*继承允许一个类继承另一个类的特征
*类型转换允许在运行时检查和解释一个类实例的类型
*解构器允许一个类实例释放任何其所被分配的资源
*用计数允许对一个类的多次引用
命名
为类和结构体使用首字母大写的驼峰命名方式,变量或者方法使用首字母小写的驼峰
*/
/// 定义
class SomeClass{} // 类
struct SomeSturct{} // 结构体
struct Resolution{ // 结构体:像素,拥有宽和高
var width = 0
var height = 0
}
class VideoPlayer{ // VideoMode类,拥有各种变量以及方法
var resolution = Resolution()
var isFullScreen = false
var name:String?
func play(){print("playing")}
func pause(){print("pause")}
func stop(){print("stop")}
}
// 创建实例
var reso = Resolution()
let vp = VideoPlayer()
// 访问属性或者方法均通过点语法
reso.width = 1280
reso.height = 720
let width = reso.width
vp.name = "Inception"
let isFull = vp.isFullScreen
vp.pause() // 调用pause方法
// 结构体构造器,
let vga = Resolution(width: 1920, height: 1080)
/// 结构体和枚举是值类型
var fourK = vga
fourK.width = 3840
fourK.height = 2160
// 只是值拷贝,改变fourK并不改变vga中的属性
print("FourK:\(fourK.width)x\(fourK.height); HD:\(vga.width)x\(vga.height)");
// 枚举也是如此,仅仅是值拷贝,
enum Companys{
case Apple, Google, Amazon, IBM
}
let aCo = Companys.Apple
var bCo = aCo
bCo = .IBM
print("A:\(aCo), B:\(bCo)")
/// 类是引用类型
let aVideoPlayer = vp
aVideoPlayer.name = "insteller"
// 改变aVideoPlayer中属性的同时改变了vp中的属性,类是引用类型
// vp和aVideoPlayer均为常量类型,改变其中属性并不改变常量值
print("aVideoPlayer:\(aVideoPlayer.name),vp:\(vp.name)")
/// 恒等运算符
// 使用"==="表示等价于,"!=="表示不等价于。用于判断是否是引用了的实例
if aVideoPlayer === vp
{
print("They are equal!")
}
// == 表示值相等 != 表示值不相等
/// 类和结构体之间的选择
/*
结构体的主要目的是用来封装少量相关简单数据值。
有理由预计一个结构体实例在赋值或传递时,封装的数据将会被拷贝而不是被引用。
任何在结构体中储存的值类型属性,也将会被拷贝,而不是被引用。
结构体不需要去继承另一个已存在类型的属性或者行为。”
*/
/// 字符串,数组,字典的赋值和复制行为
// swift中这三者均以结构体形式实现,因此均为值拷贝
// Objective C中这三者均以类形式实现,因此均为传递引用
| apache-2.0 |
jeden/kocomojo-kit | KocomojoApp/KocomojoApp/ui/tools/Styles.swift | 2 | 418 | //
// Styles.swift
// KocomojoApp
//
// Created by Antonio Bello on 1/27/15.
// Copyright (c) 2015 Elapsus. All rights reserved.
//
import Foundation
import UIKit
struct Styles {
static func defaultButton(button: UIButton) {
button.layer.cornerRadius = 2;
button.backgroundColor = UIColor(red: 0.55, green: 0.55, blue: 0.55, alpha: 1.0)
button.tintColor = UIColor.whiteColor()
}
} | mit |
hellogaojun/Swift-coding | swift学习教材案例/GuidedTour-1.2.playground/section-17.swift | 77 | 60 | shoppingList = [] // Went shopping and bought everything.
| apache-2.0 |
ps2/rileylink_ios | OmniKitUI/ViewModels/PairPodViewModel.swift | 1 | 7722 | //
// PairPodViewModel.swift
// OmniKit
//
// Created by Pete Schwamb on 3/2/20.
// Copyright © 2021 LoopKit Authors. All rights reserved.
//
import SwiftUI
import LoopKit
import LoopKitUI
import OmniKit
class PairPodViewModel: ObservableObject, Identifiable {
enum NavBarButtonAction {
case cancel
case discard
var text: String {
switch self {
case .cancel:
return LocalizedString("Cancel", comment: "Pairing interface navigation bar button text for cancel action")
case .discard:
return LocalizedString("Discard Pod", comment: "Pairing interface navigation bar button text for discard pod action")
}
}
func color(using guidanceColors: GuidanceColors) -> Color? {
switch self {
case .discard:
return guidanceColors.critical
case .cancel:
return nil
}
}
}
enum PairPodViewModelState {
case ready
case pairing
case priming(finishTime: CFTimeInterval)
case error(OmnipodPairingError)
case finished
var instructionsDisabled: Bool {
switch self {
case .ready:
return false
case .error(let error):
return !error.recoverable
default:
return true
}
}
var actionButtonAccessibilityLabel: String {
switch self {
case .ready:
return LocalizedString("Pair pod.", comment: "Pairing action button accessibility label while ready to pair")
case .pairing:
return LocalizedString("Pairing.", comment: "Pairing action button accessibility label while pairing")
case .priming:
return LocalizedString("Priming. Please wait.", comment: "Pairing action button accessibility label while priming")
case .error(let error):
return String(format: "%@ %@", error.errorDescription ?? "", error.recoverySuggestion ?? "")
case .finished:
return LocalizedString("Pod paired successfully. Continue.", comment: "Pairing action button accessibility label when pairing succeeded")
}
}
var nextActionButtonDescription: String {
switch self {
case .ready:
return LocalizedString("Pair Pod", comment: "Pod pairing action button text while ready to pair")
case .error:
return LocalizedString("Retry", comment: "Pod pairing action button text while showing error")
case .pairing:
return LocalizedString("Pairing...", comment: "Pod pairing action button text while pairing")
case .priming:
return LocalizedString("Priming...", comment: "Pod pairing action button text while priming")
case .finished:
return LocalizedString("Continue", comment: "Pod pairing action button text when paired")
}
}
var navBarButtonAction: NavBarButtonAction {
// switch self {
// case .error(_, let podCommState):
// if podCommState == .activating {
// return .discard
// }
// default:
// break
// }
return .cancel
}
var navBarVisible: Bool {
if case .error(let error) = self {
return error.recoverable
}
return true
}
var showProgressDetail: Bool {
switch self {
case .ready:
return false
default:
return true
}
}
var progressState: ProgressIndicatorState {
switch self {
case .ready, .error:
return .hidden
case .pairing:
return .indeterminantProgress
case .priming(let finishTime):
return .timedProgress(finishTime: finishTime)
case .finished:
return .completed
}
}
var isProcessing: Bool {
switch self {
case .pairing, .priming:
return true
default:
return false
}
}
var isFinished: Bool {
if case .finished = self {
return true
}
return false
}
}
var error: OmnipodPairingError? {
if case .error(let error) = state {
return error
}
return nil
}
@Published var state: PairPodViewModelState = .ready
var podIsActivated: Bool {
return false // podPairer.podCommState != .noPod
}
var backButtonHidden: Bool {
if case .pairing = state {
return true
}
if podIsActivated {
return true
}
return false
}
var didFinish: (() -> Void)?
var didRequestDeactivation: (() -> Void)?
var didCancelSetup: (() -> Void)?
var podPairer: PodPairer
init(podPairer: PodPairer) {
self.podPairer = podPairer
}
private func pair() {
state = .pairing
podPairer.pair { (status) in
DispatchQueue.main.async {
switch status {
case .failure(let error):
let pairingError = OmnipodPairingError.pumpManagerError(error)
self.state = .error(pairingError)
case .success(let duration):
if duration > 0 {
self.state = .priming(finishTime: CACurrentMediaTime() + duration)
DispatchQueue.main.asyncAfter(deadline: .now() + duration) {
self.state = .finished
}
} else {
self.state = .finished
}
}
}
}
}
public func continueButtonTapped() {
switch state {
case .error(let error):
if !error.recoverable {
self.didRequestDeactivation?()
} else {
// Retry
pair()
}
case .finished:
didFinish?()
default:
pair()
}
}
}
// Pairing recovery suggestions
enum OmnipodPairingError : LocalizedError {
case pumpManagerError(PumpManagerError)
var recoverySuggestion: String? {
switch self {
case .pumpManagerError(let error):
return error.recoverySuggestion
}
}
var errorDescription: String? {
switch self {
case .pumpManagerError(let error):
return error.errorDescription
}
}
var recoverable: Bool {
// switch self {
// case .pumpManagerError(let error):
// TODO: check which errors are recoverable
return true
// }
}
}
public protocol PodPairer {
func pair(completion: @escaping (PumpManagerResult<TimeInterval>) -> Void)
func discardPod(completion: @escaping (Bool) -> ())
}
extension OmnipodPumpManager: PodPairer {
public func discardPod(completion: @escaping (Bool) -> ()) {
}
public func pair(completion: @escaping (PumpManagerResult<TimeInterval>) -> Void) {
pairAndPrime(completion: completion)
}
}
| mit |
vmanot/swift-package-manager | Fixtures/Miscellaneous/PkgConfig/CSystemModule/Package.swift | 3 | 149 | import PackageDescription
let package = Package(
name: "CSystemModule",
pkgConfig: "libSystemModule",
providers: [.Brew("SystemModule")]
)
| apache-2.0 |
MobileToolkit/Glover-iOS | Example/Sources/AppDelegate.swift | 2 | 3283 | //
// AppDelegate.swift
// Glover iOS Example
//
// Created by Sebastian Owodzin on 24/04/2016.
// Copyright © 2016 mobiletoolkit.org. All rights reserved.
//
import UIKit
import CoreData
import Glover
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var manager: Manager!
lazy var applicationDocumentsDirectory: URL = {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}()
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Remove old db files
do {
try FileManager().removeItem(atPath: applicationDocumentsDirectory.appendingPathComponent("db.sqlite").path)
} catch {
}
// Init Glover
let model = NSManagedObjectModel(contentsOf: Bundle.main.url(forResource: "Model", withExtension: "momd")!)!
let config = Configuration(model: model)
let persistentStoreOptions = [
NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true
]
let url = self.applicationDocumentsDirectory.appendingPathComponent("db.sqlite")
config.addPersistentStoreConfiguration(PersistentStoreConfiguration(type: .SQLite, url: url, configuration: nil, options: persistentStoreOptions as [String: AnyObject]))
manager = Manager(configuration: config)
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.
manager.saveContext()
}
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:.
manager.saveContext()
}
}
| mit |
AgaKhanFoundation/WCF-iOS | Pods/Nimble/Sources/Nimble/Utils/Await.swift | 2 | 13535 | #if !os(WASI)
import CoreFoundation
import Dispatch
import Foundation
private let timeoutLeeway = DispatchTimeInterval.milliseconds(1)
private let pollLeeway = DispatchTimeInterval.milliseconds(1)
/// Stores debugging information about callers
internal struct WaitingInfo: CustomStringConvertible {
let name: String
let file: FileString
let lineNumber: UInt
var description: String {
return "\(name) at \(file):\(lineNumber)"
}
}
internal protocol WaitLock {
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt)
func releaseWaitingLock()
func isWaitingLocked() -> Bool
}
internal class AssertionWaitLock: WaitLock {
private var currentWaiter: WaitingInfo?
init() { }
func acquireWaitingLock(_ fnName: String, file: FileString, line: UInt) {
let info = WaitingInfo(name: fnName, file: file, lineNumber: line)
let isMainThread = Thread.isMainThread
nimblePrecondition(
isMainThread,
"InvalidNimbleAPIUsage",
"\(fnName) can only run on the main thread."
)
nimblePrecondition(
currentWaiter == nil,
"InvalidNimbleAPIUsage",
"""
Nested async expectations are not allowed to avoid creating flaky tests.
The call to
\t\(info)
triggered this exception because
\t\(currentWaiter!)
is currently managing the main run loop.
"""
)
currentWaiter = info
}
func isWaitingLocked() -> Bool {
return currentWaiter != nil
}
func releaseWaitingLock() {
currentWaiter = nil
}
}
internal enum AwaitResult<T> {
/// Incomplete indicates None (aka - this value hasn't been fulfilled yet)
case incomplete
/// TimedOut indicates the result reached its defined timeout limit before returning
case timedOut
/// BlockedRunLoop indicates the main runloop is too busy processing other blocks to trigger
/// the timeout code.
///
/// This may also mean the async code waiting upon may have never actually ran within the
/// required time because other timers & sources are running on the main run loop.
case blockedRunLoop
/// The async block successfully executed and returned a given result
case completed(T)
/// When a Swift Error is thrown
case errorThrown(Error)
/// When an Objective-C Exception is raised
case raisedException(NSException)
func isIncomplete() -> Bool {
switch self {
case .incomplete: return true
default: return false
}
}
func isCompleted() -> Bool {
switch self {
case .completed: return true
default: return false
}
}
}
/// Holds the resulting value from an asynchronous expectation.
/// This class is thread-safe at receiving an "response" to this promise.
internal final class AwaitPromise<T> {
private(set) internal var asyncResult: AwaitResult<T> = .incomplete
private var signal: DispatchSemaphore
init() {
signal = DispatchSemaphore(value: 1)
}
deinit {
signal.signal()
}
/// Resolves the promise with the given result if it has not been resolved. Repeated calls to
/// this method will resolve in a no-op.
///
/// @returns a Bool that indicates if the async result was accepted or rejected because another
/// value was received first.
func resolveResult(_ result: AwaitResult<T>) -> Bool {
if signal.wait(timeout: .now()) == .success {
self.asyncResult = result
return true
} else {
return false
}
}
}
internal struct AwaitTrigger {
let timeoutSource: DispatchSourceTimer
let actionSource: DispatchSourceTimer?
let start: () throws -> Void
}
/// Factory for building fully configured AwaitPromises and waiting for their results.
///
/// This factory stores all the state for an async expectation so that Await doesn't
/// doesn't have to manage it.
internal class AwaitPromiseBuilder<T> {
let awaiter: Awaiter
let waitLock: WaitLock
let trigger: AwaitTrigger
let promise: AwaitPromise<T>
internal init(
awaiter: Awaiter,
waitLock: WaitLock,
promise: AwaitPromise<T>,
trigger: AwaitTrigger) {
self.awaiter = awaiter
self.waitLock = waitLock
self.promise = promise
self.trigger = trigger
}
func timeout(_ timeoutInterval: DispatchTimeInterval, forcefullyAbortTimeout: DispatchTimeInterval) -> Self {
// = Discussion =
//
// There's a lot of technical decisions here that is useful to elaborate on. This is
// definitely more lower-level than the previous NSRunLoop based implementation.
//
//
// Why Dispatch Source?
//
//
// We're using a dispatch source to have better control of the run loop behavior.
// A timer source gives us deferred-timing control without having to rely as much on
// a run loop's traditional dispatching machinery (eg - NSTimers, DefaultRunLoopMode, etc.)
// which is ripe for getting corrupted by application code.
//
// And unlike dispatch_async(), we can control how likely our code gets prioritized to
// executed (see leeway parameter) + DISPATCH_TIMER_STRICT.
//
// This timer is assumed to run on the HIGH priority queue to ensure it maintains the
// highest priority over normal application / test code when possible.
//
//
// Run Loop Management
//
// In order to properly interrupt the waiting behavior performed by this factory class,
// this timer stops the main run loop to tell the waiter code that the result should be
// checked.
//
// In addition, stopping the run loop is used to halt code executed on the main run loop.
trigger.timeoutSource.schedule(
deadline: DispatchTime.now() + timeoutInterval,
repeating: .never,
leeway: timeoutLeeway
)
trigger.timeoutSource.setEventHandler {
guard self.promise.asyncResult.isIncomplete() else { return }
let timedOutSem = DispatchSemaphore(value: 0)
let semTimedOutOrBlocked = DispatchSemaphore(value: 0)
semTimedOutOrBlocked.signal()
let runLoop = CFRunLoopGetMain()
#if canImport(Darwin)
let runLoopMode = CFRunLoopMode.defaultMode.rawValue
#else
let runLoopMode = kCFRunLoopDefaultMode
#endif
CFRunLoopPerformBlock(runLoop, runLoopMode) {
if semTimedOutOrBlocked.wait(timeout: .now()) == .success {
timedOutSem.signal()
semTimedOutOrBlocked.signal()
if self.promise.resolveResult(.timedOut) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
// potentially interrupt blocking code on run loop to let timeout code run
CFRunLoopStop(runLoop)
let now = DispatchTime.now() + forcefullyAbortTimeout
let didNotTimeOut = timedOutSem.wait(timeout: now) != .success
let timeoutWasNotTriggered = semTimedOutOrBlocked.wait(timeout: .now()) == .success
if didNotTimeOut && timeoutWasNotTriggered {
if self.promise.resolveResult(.blockedRunLoop) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
}
return self
}
/// Blocks for an asynchronous result.
///
/// @discussion
/// This function must be executed on the main thread and cannot be nested. This is because
/// this function (and it's related methods) coordinate through the main run loop. Tampering
/// with the run loop can cause undesirable behavior.
///
/// This method will return an AwaitResult in the following cases:
///
/// - The main run loop is blocked by other operations and the async expectation cannot be
/// be stopped.
/// - The async expectation timed out
/// - The async expectation succeeded
/// - The async expectation raised an unexpected exception (objc)
/// - The async expectation raised an unexpected error (swift)
///
/// The returned AwaitResult will NEVER be .incomplete.
func wait(_ fnName: String = #function, file: FileString = #file, line: UInt = #line) -> AwaitResult<T> {
waitLock.acquireWaitingLock(
fnName,
file: file,
line: line)
let capture = NMBExceptionCapture(handler: ({ exception in
_ = self.promise.resolveResult(.raisedException(exception))
}), finally: ({
self.waitLock.releaseWaitingLock()
}))
capture.tryBlock {
do {
try self.trigger.start()
} catch let error {
_ = self.promise.resolveResult(.errorThrown(error))
}
self.trigger.timeoutSource.resume()
while self.promise.asyncResult.isIncomplete() {
// Stopping the run loop does not work unless we run only 1 mode
_ = RunLoop.current.run(mode: .default, before: .distantFuture)
}
self.trigger.timeoutSource.cancel()
if let asyncSource = self.trigger.actionSource {
asyncSource.cancel()
}
}
return promise.asyncResult
}
}
internal class Awaiter {
let waitLock: WaitLock
let timeoutQueue: DispatchQueue
let asyncQueue: DispatchQueue
internal init(
waitLock: WaitLock,
asyncQueue: DispatchQueue,
timeoutQueue: DispatchQueue) {
self.waitLock = waitLock
self.asyncQueue = asyncQueue
self.timeoutQueue = timeoutQueue
}
private func createTimerSource(_ queue: DispatchQueue) -> DispatchSourceTimer {
return DispatchSource.makeTimerSource(flags: .strict, queue: queue)
}
func performBlock<T>(
file: FileString,
line: UInt,
_ closure: @escaping (@escaping (T) -> Void) throws -> Void
) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
var completionCount = 0
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: nil) {
try closure { result in
completionCount += 1
if completionCount < 2 {
func completeBlock() {
if promise.resolveResult(.completed(result)) {
CFRunLoopStop(CFRunLoopGetMain())
}
}
if Thread.isMainThread {
completeBlock()
} else {
DispatchQueue.main.async { completeBlock() }
}
} else {
fail("waitUntil(..) expects its completion closure to be only called once",
file: file, line: line)
}
}
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
func poll<T>(_ pollInterval: DispatchTimeInterval, closure: @escaping () throws -> T?) -> AwaitPromiseBuilder<T> {
let promise = AwaitPromise<T>()
let timeoutSource = createTimerSource(timeoutQueue)
let asyncSource = createTimerSource(asyncQueue)
let trigger = AwaitTrigger(timeoutSource: timeoutSource, actionSource: asyncSource) {
let interval = pollInterval
asyncSource.schedule(deadline: .now(), repeating: interval, leeway: pollLeeway)
asyncSource.setEventHandler {
do {
if let result = try closure() {
if promise.resolveResult(.completed(result)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
} catch let error {
if promise.resolveResult(.errorThrown(error)) {
CFRunLoopStop(CFRunLoopGetCurrent())
}
}
}
asyncSource.resume()
}
return AwaitPromiseBuilder(
awaiter: self,
waitLock: waitLock,
promise: promise,
trigger: trigger)
}
}
internal func pollBlock(
pollInterval: DispatchTimeInterval,
timeoutInterval: DispatchTimeInterval,
file: FileString,
line: UInt,
fnName: String = #function,
expression: @escaping () throws -> Bool) -> AwaitResult<Bool> {
let awaiter = NimbleEnvironment.activeInstance.awaiter
let result = awaiter.poll(pollInterval) { () throws -> Bool? in
if try expression() {
return true
}
return nil
}.timeout(timeoutInterval, forcefullyAbortTimeout: timeoutInterval.divided).wait(fnName, file: file, line: line)
return result
}
#endif // #if !os(WASI)
| bsd-3-clause |
nFiction/StackOverflow | StackOverflowTests/StackOverflowTests.swift | 1 | 991 | //
// StackOverflowTests.swift
// StackOverflowTests
//
// Created by Bruno da Luz on 3/31/16.
// Copyright © 2016 nFiction. All rights reserved.
//
import XCTest
@testable import StackOverflow
class StackOverflowTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| mit |
jackcook/interface | Interface/AppDelegate.swift | 1 | 1840 | //
// AppDelegate.swift
// Interface
//
// Created by Jack Cook on 4/2/16.
// Copyright © 2016 Jack Cook. All rights reserved.
//
import UIKit
var language: String? {
get {
return NSUserDefaults.standardUserDefaults().stringForKey("InterfaceLanguage")
}
set(newValue) {
NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "InterfaceLanguage")
}
}
var lang: String {
get {
return language!.componentsSeparatedByString("-")[0]
}
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if language != nil {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let avc = storyboard.instantiateViewControllerWithIdentifier("ArticlesViewController") as! ArticlesViewController
let navController = UINavigationController()
window?.rootViewController = navController
navController.pushViewController(avc, animated: false)
}
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
guard let host = url.host else {
return true
}
switch host {
case "auth":
if let component = url.pathComponents?[1] {
switch component {
case "quizlet":
Quizlet.sharedInstance.handleAuthorizationResponse(url)
default:
break
}
}
default:
break
}
return true
}
}
| mit |
daltoniam/Starscream | examples/WebSocketsOrgEcho/WebSocketsOrgEcho/ViewController.swift | 1 | 1054 | //
// ViewController.swift
// WebSocketsOrgEcho
//
// Created by Kristaps Grinbergs on 08/10/2018.
// Copyright © 2018 Starscream. All rights reserved.
//
import UIKit
import Starscream
class ViewController: UIViewController, WebSocketDelegate {
var socket: WebSocket = WebSocket(url: URL(staticString: "wss://echo.websocket.org"))
func websocketDidConnect(socket: WebSocketClient) {
print("websocketDidConnect")
}
func websocketDidDisconnect(socket: WebSocketClient, error: Error?) {
print("websocketDidDisconnect", error ?? "")
}
func websocketDidReceiveMessage(socket: WebSocketClient, text: String) {
print("websocketDidReceiveMessage", text)
}
func websocketDidReceiveData(socket: WebSocketClient, data: Data) {
print("websocketDidReceiveData", data)
}
override func viewDidLoad() {
super.viewDidLoad()
socket.delegate = self
}
@IBAction func connect(_ sender: Any) {
socket.connect()
}
}
| apache-2.0 |
MonkeyRing/DragBackNavigationController | DragNavigationController/DragNavigationController/AViewController.swift | 1 | 431 | //
// AViewController.swift
// DragNavigationController
//
// Created by FundSmart IOS on 16/5/21.
// Copyright © 2016年 黄海龙. All rights reserved.
//
import UIKit
class AViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
dismiss(animated: true, completion: nil)
}
}
| mit |
playbasis/native-sdk-ios | PlaybasisSDK/Classes/PBModel/PBLeaderBoard.swift | 1 | 1816 | //
// PBLeaderBoard.swift
// Playbook
//
// Created by Nuttapol Thitaweera on 6/24/2559 BE.
// Copyright © 2559 smartsoftasia. All rights reserved.
//
import UIKit
import ObjectMapper
public class PBLeaderBoard: PBModel {
public var dateCompleted:NSDate?
public var dateJoined:NSDate?
public var status:String! = ""
public var current:Int! = 0
public var goal:Int! = 0
public var player:PBPlayerBasic?
public var rank:Int! = 0
override public func mapping(map: Map) {
super.mapping(map)
self.dateCompleted <- (map["date_completed"],ISO8601DateTransform())
self.dateJoined <- (map["date_join"], ISO8601DateTransform())
self.status <- map["status"]
self.current <- map["current"]
self.goal <- map["goal"]
self.player <- map["player"]
self.rank <- map["rank"]
}
public override init() {
super.init()
}
required public init?(_ map: Map) {
super.init(map)
}
init(apiResponse:PBApiResponse) {
super.init()
Mapper<PBLeaderBoard>().map(apiResponse.parsedJson!["player_data"], toObject: self)
}
class func pbLeaderBoardDataFromApiResponse(apiResponse:PBApiResponse) -> (leaderBoardList:[PBLeaderBoard], playerData:PBLeaderBoard?) {
var pbLeaderBoardList:[PBLeaderBoard] = []
pbLeaderBoardList = Mapper<PBLeaderBoard>().mapArray(apiResponse.parsedJson!["result"])!
if let playerDataJson = apiResponse.parsedJson!["player_data"], let playerData:PBLeaderBoard = Mapper<PBLeaderBoard>().map(playerDataJson) {
return (leaderBoardList:pbLeaderBoardList, playerData:playerData)
}
else {
return (leaderBoardList:pbLeaderBoardList, playerData:nil)
}
}
}
| mit |
arietis/codility-swift | 10.3.swift | 1 | 770 | public func solution(inout A : [Int]) -> Int {
// write your code in Swift 2.2
let n = A.count
if n < 3 {
return 0
}
var peaks: [Int] = []
for i in 1..<n - 1 {
if A[i - 1] < A[i] && A[i] > A[i + 1] {
peaks.append(i)
}
}
for var i = n; i > 0; i -= 1 {
if n % i != 0 {
continue
}
let blockSize = n / i
var currentBlock = 0
for j in peaks {
if j / blockSize > currentBlock {
break
}
if j / blockSize == currentBlock {
currentBlock += 1
}
}
if currentBlock == i {
return i
}
}
return 0
}
| mit |
pixeldock/RxAppState | Package.swift | 1 | 755 | // swift-tools-version:5.2
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "RxAppState",
platforms: [
.iOS(.v10)
],
products: [
.library(
name: "RxAppState",
targets: ["RxAppState"])
],
dependencies: [
.package(url: "https://github.com/ReactiveX/RxSwift.git", .upToNextMajor(from: "6.2.0"))
],
targets: [
.target(
name: "RxAppState",
dependencies: [
"RxSwift",
.product(name: "RxCocoa", package: "RxSwift")
],
path: "Pod/Classes"
)
],
swiftLanguageVersions: [.v5]
)
| mit |
benlangmuir/swift | test/Serialization/Recovery/implementation-only-missing.swift | 11 | 3973 | // Recover from missing types hidden behind an importation-only when indexing
// a system module.
// rdar://problem/52837313
// RUN: %empty-directory(%t)
//// Build the private module, the public module and the client app normally.
//// Force the public module to be system with an underlying Clang module.
// RUN: %target-swift-frontend -emit-module -DPRIVATE_LIB %s -module-name private_lib -emit-module-path %t/private_lib.swiftmodule
// RUN: %target-swift-frontend -emit-module -DPUBLIC_LIB %s -module-name public_lib -emit-module-path %t/public_lib.swiftmodule -I %t -I %S/Inputs/implementation-only-missing -import-underlying-module
//// The client app should build OK without the private module. Removing the
//// private module is superfluous but makes sure that it's not somehow loaded.
// RUN: rm %t/private_lib.swiftmodule
// RUN: %target-swift-frontend -typecheck -DCLIENT_APP %s -I %t -index-system-modules -index-store-path %t
// RUN: %target-swift-frontend -typecheck -DCLIENT_APP %s -I %t -D FAIL_TYPECHECK -verify
// RUN: %target-swift-frontend -emit-sil -DCLIENT_APP %s -I %t -module-name client
//// Printing the public module should not crash when checking for overrides of
//// methods from the private module.
// RUN: %target-swift-ide-test -print-module -module-to-print=public_lib -source-filename=x -skip-overrides -I %t
#if PRIVATE_LIB
@propertyWrapper
public struct IoiPropertyWrapper<V> {
var content: V
public init(_ v: V) {
content = v
}
public var wrappedValue: V {
return content
}
}
public struct HiddenGenStruct<A: HiddenProtocol> {
public init() {}
}
public protocol HiddenProtocol {
associatedtype Value
}
public protocol HiddenProtocol2 {}
public protocol HiddenProtocolWithOverride {
func hiddenOverride()
}
public class HiddenClass {}
#elseif PUBLIC_LIB
@_implementationOnly import private_lib
struct LibProtocolConstraint { }
protocol LibProtocolTABound { }
struct LibProtocolTA: LibProtocolTABound { }
protocol LibProtocol {
associatedtype TA: LibProtocolTABound = LibProtocolTA
func hiddenRequirement<A>(
param: HiddenGenStruct<A>
) where A.Value == LibProtocolConstraint
}
extension LibProtocol where TA == LibProtocolTA {
func hiddenRequirement<A>(
param: HiddenGenStruct<A>
) where A.Value == LibProtocolConstraint { }
}
public struct PublicStruct: LibProtocol {
typealias TA = LibProtocolTA
public init() { }
public var nonWrappedVar: String = "some text"
}
struct StructWithOverride: HiddenProtocolWithOverride {
func hiddenOverride() {}
}
internal protocol RefinesHiddenProtocol: HiddenProtocol {
}
public struct PublicStructConformsToHiddenProtocol: RefinesHiddenProtocol {
public typealias Value = Int
public init() { }
}
public class SomeClass {
func funcUsingIoiType(_ a: HiddenClass) {}
}
// Check that we recover from a reference to an implementation-only
// imported type in a protocol composition. rdar://78631465
protocol CompositionMemberInheriting : HiddenProtocol2 {}
protocol CompositionMemberSimple {}
protocol InheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {}
struct StructInheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {}
class ClassInheritingFromComposition : CompositionMemberInheriting & CompositionMemberSimple {}
protocol InheritingFromCompositionDirect : CompositionMemberSimple & HiddenProtocol2 {}
#elseif CLIENT_APP
import public_lib
var s = PublicStruct()
print(s.nonWrappedVar)
var p = PublicStructConformsToHiddenProtocol()
print(p)
#if FAIL_TYPECHECK
// Access to a missing member on an AnyObject triggers a typo correction
// that looks at *all* class members. rdar://79427805
class ClassUnrelatedToSomeClass {}
var something = ClassUnrelatedToSomeClass() as AnyObject
something.triggerTypoCorrection = 123 // expected-error {{value of type 'AnyObject' has no member 'triggerTypoCorrection'}}
#endif
#endif
| apache-2.0 |
benlangmuir/swift | validation-test/compiler_crashers_fixed/24769-std-function-func-swift-type-subst.swift | 65 | 440 | // 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
class c<U,C{class A{class a<T{enum S<T>:a
| apache-2.0 |
crazytravel/NetReader | NetReader/Views/Me/MeViewController.swift | 1 | 852 | //
// MeViewController.swift
// NetReader
//
// Created by 王硕 on 26/12/2016.
// Copyright © 2016 Sean. All rights reserved.
//
import UIKit
class MeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
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 prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit |
isRaining/Swift30days | 1_day/007可选项的判断/007可选项的判断/AppDelegate.swift | 1 | 2186 | //
// AppDelegate.swift
// 007可选项的判断
//
// Created by 张正雨 on 2017/5/16.
// Copyright © 2017年 张正雨. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. 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 active 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 |
CoderLiLe/Swift | 类/main.swift | 1 | 1493 | //
// main.swift
// 类
//
// Created by LiLe on 15/4/4.
// Copyright (c) 2015年 LiLe. All rights reserved.
//
import Foundation
/*
对于OC和Swift的初始化,苹果官方给了一些很合理的解释,请点开这里:https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html
*/
/*
定义Swift初始化方法,必须遵循三条规则:
1.指定构造器必须调用它直接父类的指定构造器方法
2.便利构造器必须调用同一类中定义的其他初始化方法
3.便利构造器在最后必须调用一个指定构造器。
*/
/*
类的基本定义
Swift中的结构体和类非常相似, 但是又有不同之处
类是具有相同属性和方法的抽象
格式:
class 类名称 {
类的属性和方法
}
*/
class Rect {
var width:Double = 0.0
var height:Double = 0.0
func show() -> Void{
print("width = \(width) height = \(height)")
}
}
// 类没有逐一构造器
//var r1 = Rect(width: 10.0, height: 10.0)
var r1 = Rect()
r1.show()
var r2 = r1
r2.show()
// 类是引用类型, 结构体之间的赋值其实是将r2指向了r1的存储控件, 所以他们是两个只想同一块存储空间, 修改其中一个会影响到另外一个
r1.width = 99
r1.show()
r2.show()
/*
恒等运算符, 用于判断是否是同一个实例, 也就是是否指向同一块存储空间
=== !==
*/
var r3 = Rect()
if r1 === r3
{
print("指向同一块存储空间")
}
| mit |
Dimillian/HackerSwifter | Hacker Swifter/Hacker Swifter/Extensions/HTMLString.swift | 1 | 2629 | //
// HTMLString.swift
// HackerSwifter
//
// Created by Thomas Ricouard on 18/07/14.
// Copyright (c) 2014 Thomas Ricouard. All rights reserved.
//
import Foundation
extension String {
static func stringByRemovingHTMLEntities(string: String) -> String {
var result = string
result = result.stringByReplacingOccurrencesOfString("<p>", withString: "\n\n", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("</p>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<i>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("</i>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("&", withString: "&", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString(">", withString: ">", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("'", withString: "'", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("/", withString: "/", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString(""", withString: "\"", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<", withString: "<", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<", withString: "<", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString(">", withString: ">", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("&", withString: "&", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("<pre><code>", withString: "", options: .CaseInsensitiveSearch, range: nil)
result = result.stringByReplacingOccurrencesOfString("</code></pre>", withString: "", options: .CaseInsensitiveSearch, range: nil)
let regex = try? NSRegularExpression(pattern: "<a[^>]+href=\"(.*?)\"[^>]*>.*?</a>",
options: NSRegularExpressionOptions.CaseInsensitive)
result = regex!.stringByReplacingMatchesInString(result, options: [], range: NSMakeRange(0, result.utf16.count), withTemplate: "$1")
return result
}
} | mit |
mtransitapps/mtransit-for-ios | MonTransit/Source/SQL/SQLHelper/BusDataProviderHelper.swift | 1 | 3137 | //
// BusDataProviderHelper.swift
// SidebarMenu
//
// Created by Thibault on 15-12-17.
// Copyright © 2015 Thibault. All rights reserved.
//
import UIKit
import SQLite
class BusDataProviderHelper {
private let routes = Table("route")
private let id = Expression<Int>("_id")
private let shortname = Expression<String>("short_name")
private let longName = Expression<String>("long_name")
private let color = Expression<String>("color")
private var busList = [BusObject]()
init()
{
}
func createRoutes(iAgency:Agency, iSqlCOnnection:Connection) -> Bool
{
do {
let wStopRawType = iAgency.getMainFilePath()
let wFileText = iAgency.getZipData().getDataFileFromZip(iAgency.mGtfsRoute, iDocumentName: wStopRawType)
if wFileText != ""
{
let wStops = wFileText.stringByReplacingOccurrencesOfString("'", withString: "").componentsSeparatedByString("\n")
let docsTrans = try! iSqlCOnnection.prepare("INSERT INTO ROUTE (_id, short_name, long_name, color) VALUES (?,?,?,?)")
try iSqlCOnnection.transaction(.Deferred) { () -> Void in
for wStop in wStops
{
let wStopFormated = wStop.componentsSeparatedByString(",")
if wStopFormated.count == 4{
try docsTrans.run(Int(wStopFormated[0])!, wStopFormated[1], wStopFormated[2], wStopFormated[3])
}
}
}
}
return true
}
catch {
print("insertion failed: \(error)")
return false
}
}
func retrieveRouteName(iId:Int)
{
let wRoutes = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(routes)
for route in wRoutes
{
busList.append(BusObject(iBusId: route[id], iBusName: route[longName],iBusNumber: route[shortname],iBusColor: route[color]))
}
}
func retrieveRouteById(iRouteId:Int, iId:Int) -> BusObject
{
let wRoute = try! SQLProvider.sqlProvider.mainDatabase(iId).prepare(routes.filter(id == iRouteId))
for route in wRoute
{
return BusObject(iBusId: route[id], iBusName: route[longName],iBusNumber: route[shortname],iBusColor: route[color])
}
return BusObject()
}
func retrieveLongName(index:Int) -> (wlongName: String, wshortName: String, iColor: String)
{
return (busList[index].getBusName(), busList[index].getBusNumber(), busList[index].getBusColor())
}
func retrieveBusAtIndex(iBusId:Int) -> BusObject
{
return busList[iBusId]
}
func retrieveBus(iBusId:Int) -> BusObject!
{
for wBus in busList
{
if wBus.getBusId() == iBusId{
return wBus
}
}
return nil
}
func totalRoutes() -> Int
{
return busList.count
}
}
| apache-2.0 |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/GroupDetails/GroupParticipantsDetail/GroupParticipantsDetailViewModel.swift | 1 | 4222 | //
// Wire
// Copyright (C) 2018 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 Foundation
import WireDataModel
fileprivate extension String {
var isValidQuery: Bool {
return !isEmpty && self != "@"
}
}
typealias GroupParticipantsDetailConversation = GroupDetailsConversationType & StableRandomParticipantsProvider
final class GroupParticipantsDetailViewModel: NSObject, SearchHeaderViewControllerDelegate, ZMConversationObserver {
private var internalParticipants: [UserType]
private var filterQuery: String?
let selectedParticipants: [UserType]
let conversation: GroupParticipantsDetailConversation
var participantsDidChange: (() -> Void)?
fileprivate var token: NSObjectProtocol?
var indexPathOfFirstSelectedParticipant: IndexPath? {
guard let user = selectedParticipants.first as? ZMUser else { return nil }
guard let row = (internalParticipants.firstIndex {
($0 as? ZMUser)?.remoteIdentifier == user.remoteIdentifier
}) else { return nil }
let section = user.isGroupAdmin(in: conversation) ? 0 : 1
return IndexPath(row: row, section: section)
}
var participants = [UserType]() {
didSet {
computeParticipantGroups()
participantsDidChange?()
}
}
var admins = [UserType]()
var members = [UserType]()
init(selectedParticipants: [UserType],
conversation: GroupParticipantsDetailConversation) {
internalParticipants = conversation.sortedOtherParticipants
self.conversation = conversation
self.selectedParticipants = selectedParticipants.sorted { $0.name < $1.name }
super.init()
if let conversation = conversation as? ZMConversation {
token = ConversationChangeInfo.add(observer: self, for: conversation)
}
computeVisibleParticipants()
}
private func computeVisibleParticipants() {
guard let query = filterQuery,
query.isValidQuery else {
return participants = internalParticipants
}
participants = (internalParticipants as NSArray).filtered(using: filterPredicate(for: query)) as! [UserType]
}
private func computeParticipantGroups() {
admins = participants.filter({$0.isGroupAdmin(in: conversation)})
members = participants.filter({!$0.isGroupAdmin(in: conversation)})
}
private func filterPredicate(for query: String) -> NSPredicate {
let trimmedQuery = query.trim()
var predicates = [
NSPredicate(format: "name contains[cd] %@", trimmedQuery),
NSPredicate(format: "handle contains[cd] %@", trimmedQuery)
]
if query.hasPrefix("@") {
predicates.append(.init(format: "handle contains[cd] %@", String(trimmedQuery.dropFirst())))
}
return NSCompoundPredicate(orPredicateWithSubpredicates: predicates)
}
func conversationDidChange(_ changeInfo: ConversationChangeInfo) {
guard changeInfo.participantsChanged else { return }
internalParticipants = conversation.sortedOtherParticipants
computeVisibleParticipants()
}
// MARK: - SearchHeaderViewControllerDelegate
func searchHeaderViewController(
_ searchHeaderViewController: SearchHeaderViewController,
updatedSearchQuery query: String
) {
filterQuery = query
computeVisibleParticipants()
}
func searchHeaderViewControllerDidConfirmAction(_ searchHeaderViewController: SearchHeaderViewController) {
// no-op
}
}
| gpl-3.0 |
JackieQu/QP_DouYu | QP_DouYu/QP_DouYu/Classes/Home/View/AmuseMenuViewCell.swift | 1 | 1581 | //
// AmuseMenuViewCell.swift
// QP_DouYu
//
// Created by JackieQu on 2017/3/8.
// Copyright © 2017年 JackieQu. All rights reserved.
//
import UIKit
private let kGameCellID = "kGameCellID"
class AmuseMenuViewCell: UICollectionViewCell {
var groups : [AnchorGroup]? {
didSet {
collectionView.reloadData()
}
}
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
collectionView.register(UINib(nibName: "CollectionViewGameCell", bundle: nil), forCellWithReuseIdentifier: kGameCellID)
}
override func layoutSubviews() {
super.layoutSubviews()
let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
let itemW = collectionView.bounds.width / 4
let itemH = collectionView.bounds.height / 2
layout.itemSize = CGSize(width: itemW, height: itemH)
}
}
extension AmuseMenuViewCell : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return groups?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kGameCellID, for: indexPath) as! CollectionViewGameCell
cell.clipsToBounds = true
cell.baseGame = groups![indexPath.item]
return cell
}
}
| mit |
Nekitosss/tableAnimator | Sources/TableAnimator/TableAnimationApplier.swift | 1 | 21209 | //
// TableAnimationApplier.swift
// NPTableAnimator
//
// Created by Nikita Patskov on 14.11.17.
//
import UIKit
#if os(iOS)
private var tableAssociatedObjectHandle: UInt8 = 0
private var collectionAssociatedObjectHandle: UInt8 = 0
private let monitor = NSObject()
#if swift(>=4.2)
public typealias UITableViewRowAnimation = UITableView.RowAnimation
#endif
/// TableView rows animation style set.
public struct UITableViewRowAnimationSet {
let insert: UITableViewRowAnimation
let delete: UITableViewRowAnimation
let reload: UITableViewRowAnimation
public init(insert: UITableViewRowAnimation, delete: UITableViewRowAnimation, reload: UITableViewRowAnimation) {
self.insert = insert
self.delete = delete
self.reload = reload
}
}
extension UITableView: EmptyCheckableSequence {
var isEmpty: Bool {
let block: () -> Bool = {
let numberOfSections = (self.dataSource?.numberOfSections?(in: self)) ?? 0
let rowsCount: Int = (0 ..< numberOfSections)
.reduce(0) { $0 + (self.dataSource?.tableView(self, numberOfRowsInSection: $1) ?? 0) }
return rowsCount == 0
}
if Thread.isMainThread {
return block()
} else {
return DispatchQueue.main.sync(execute: block)
}
}
/// Use this for applying changes for UITableView.
///
/// - Parameters:
/// - owner: Apply moves to Operation queue, so you need to pass owner for capturing.
/// - newList: New list that should be presented in collection view.
/// - getCurrentListBlock: Block for getting current screen list. Called from main thread.
/// - animator: Instance of TableAnimator for calculating changes.
/// - animated: If you dont want to animate changes, just pass *false*, otherwise, pass *true*.
/// - options: Additional options for animations applying.
/// - from: Initial list, which we got from *getCurrentListBlock()*.
/// - to: New list to set, which you pass in *newList*.
/// - setNewListBlock: Block for changing current screen list to passed *newList*. Called from main thread.
/// - rowAnimations: Specific UITableViewRowAnimations that will be passed in all animation type during applying.
/// - completion: Block for capturing animation completion. Called from main thread.
/// - error: Block for capturing error during changes calculation. When we got error in changes, we call *setNewListBlock* and *tableView.reloadData()*, then error block called
/// - tableError: TableAnimatorError
public func apply<T, O: AnyObject>(owner: O, newList: [T], animator: TableAnimator<T>, animated: Bool, options: ApplyAnimationOptions = [], getCurrentListBlock: @escaping (_ owner: O) -> [T], setNewListBlock: @escaping ((owner: O, newList: [T])) -> Void, rowAnimations: UITableViewRowAnimationSet, completion: (() -> Void)?, error: ((_ tableError: Error) -> Void)?) {
if options.contains(.cancelPreviousAddedOperations) {
self.getApplyQueue().cancelAllOperations()
}
if options.contains(.withoutActuallyRefreshTable) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner] in
guard let strongO = owner else { return }
setNewListBlock((strongO, newList))
}
}
return
} else if !animated || (self.isEmpty && options.contains(.withoutAnimationForEmptyTable)) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner, weak self] in
guard let strongO = owner, let strong = self else { return }
setNewListBlock((strongO, newList))
strong.reloadData()
completion?()
}
}
return
}
let setAnimationsClosure: (UITableView, TableAnimations) -> Void = { table, animations in
let animations = table.applyOptions(options: options, to: animations)
table.insertSections(animations.sections.toInsert, with: rowAnimations.insert)
table.deleteSections(animations.sections.toDelete, with: rowAnimations.delete)
table.reloadSections(animations.sections.toUpdate, with: rowAnimations.reload)
for (from, to) in animations.sections.toMove {
table.moveSection(from, toSection: to)
}
table.insertRows(at: animations.cells.toInsert, with: rowAnimations.insert)
table.deleteRows(at: animations.cells.toDelete, with: rowAnimations.delete)
table.reloadRows(at: animations.cells.toUpdate, with: rowAnimations.reload)
for (from, to) in animations.cells.toMove {
table.moveRow(at: from, to: to)
}
}
let safeApplyClosure: (O, DispatchSemaphore, TableAnimations) -> Void = { [weak self] anOwner, semaphore, animations in
guard let strong = self, strong.dataSource != nil else {
return
}
if #available(iOS 11, *) {
strong.performBatchUpdates({
setNewListBlock((anOwner, newList))
setAnimationsClosure(strong, animations)
}, completion: { _ in
if animations.cells.toDeferredUpdate.isEmpty {
completion?()
}
semaphore.signal()
})
} else {
strong.beginUpdates()
setNewListBlock((anOwner, newList))
setAnimationsClosure(strong, animations)
strong.endUpdates()
if animations.cells.toDeferredUpdate.isEmpty {
completion?()
}
semaphore.signal()
}
}
let safeDeferredApplyClosure: (O, DispatchSemaphore, [IndexPath]) -> Void = { [weak self] _, semaphore, toDeferredUpdate in
guard let strong = self, strong.dataSource != nil else {
return
}
let toDeferredUpdate = strong.applyOptions(options: options, toDeferredUpdatePaths: toDeferredUpdate)
if #available(iOS 11, *) {
strong.performBatchUpdates({
strong.reloadRows(at: toDeferredUpdate, with: rowAnimations.reload)
}, completion: { _ in
completion?()
semaphore.signal()
})
} else {
strong.beginUpdates()
strong.reloadRows(at: toDeferredUpdate, with: rowAnimations.reload)
strong.endUpdates()
completion?()
semaphore.signal()
}
}
let onAnimationsError: (O, Error) -> Void = { [weak self] owner, anError in
setNewListBlock((owner, newList))
self?.reloadData()
error?(anError)
}
safeApplier.apply(owner: owner,
newList: newList,
options: options,
animator: animator,
getCurrentListBlock: getCurrentListBlock,
mainPerform: safeApplyClosure,
deferredPerform: safeDeferredApplyClosure,
onAnimationsError: onAnimationsError)
}
/// Use this for applying changes for UITableView.
///
/// - Parameters:
/// - owner: Apply moves to Operation queue, so you need to pass owner for capturing.
/// - newList: New list that should be presented in collection view.
/// - getCurrentListBlock: Block for getting current screen list. Called from main thread.
/// - animator: Instance of TableAnimator for calculating changes.
/// - animated: If you dont want to animate changes, just pass *false*, otherwise, pass *true*.
/// - options: Additional options for animations applying.
/// - from: Initial list, which we got from *getCurrentListBlock()*.
/// - to: New list to set, which you pass in *newList*.
/// - setNewListBlock: Block for changing current screen list to passed *newList*. Called from main thread.
/// - rowAnimation: UITableViewRowAnimation that will be passed in all animation type during applying.
/// - completion: Block for capturing animation completion. Called from main thread.
/// - error: Block for capturing error during changes calculation. When we got error in changes, we call *setNewListBlock* and *tableView.reloadData()*, then error block called
/// - tableError: TableAnimatorError
public func apply<T, O: AnyObject>(owner: O, newList: [T], animator: TableAnimator<T>, animated: Bool, options: ApplyAnimationOptions = [], getCurrentListBlock: @escaping (_ owner: O) -> [T], setNewListBlock: @escaping ((owner: O, newList: [T])) -> Void, rowAnimation: UITableViewRowAnimation, completion: (() -> Void)? = nil, error: ((_ tableError: Error) -> Void)? = nil) {
let animationSet = UITableViewRowAnimationSet(insert: rowAnimation, delete: rowAnimation, reload: rowAnimation)
self.apply(owner: owner, newList: newList, animator: animator, animated: animated, options: options, getCurrentListBlock: getCurrentListBlock, setNewListBlock: setNewListBlock, rowAnimations: animationSet, completion: completion, error: error)
}
/// Use this function when you need synchronize something with serialized animation queue.
///
/// - Returns: Queue that used for animations synchronizing.
public func getApplyQueue() -> OperationQueue {
return safeApplier.applyQueue
}
/// User this when you want to provide your own operation queue for animations serializing.
/// - Note: You **had to** use serialized queue!
///
/// - Parameter operationQueue: Operation queue that will be used for animatino synchronizing.
/// - Returns: *true* if queue was successfully set, *false* if table already have queue for animations.
public func provideApplyQueue(_ operationQueue: OperationQueue) -> Bool {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if (objc_getAssociatedObject(self, &tableAssociatedObjectHandle) as? SafeApplier) != nil {
return false
} else {
let applier = SafeApplier(associatedTable: self, operationQueue: operationQueue)
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return true
}
}
private var safeApplier: SafeApplier {
get {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if let applier = objc_getAssociatedObject(self, &tableAssociatedObjectHandle) as? SafeApplier {
return applier
} else {
let applier = SafeApplier(associatedTable: self)
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return applier
}
}
set {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
private func applyOptions(options: ApplyAnimationOptions, to animations: (cells: CellsAnimations, sections: SectionsAnimations)) -> (cells: CellsAnimations, sections: SectionsAnimations) {
var animations = animations
if let visibleRows = self.indexPathsForVisibleRows,
let firstResponderIndex = visibleRows.first(where: { self.cellForRow(at: $0)?.isActuallyResponder == true }) {
if options.contains(.excludeFirstResponderCellFromReload) {
animations.cells.toUpdate = animations.cells.toUpdate.filter({ $0 != firstResponderIndex })
}
if options.contains(.excludeFirstResponderSectionFromReload) {
animations.sections.toUpdate.remove(firstResponderIndex.section)
}
}
return animations
}
private func applyOptions(options: ApplyAnimationOptions, toDeferredUpdatePaths: [IndexPath]) -> [IndexPath] {
if let visibleRows = self.indexPathsForVisibleRows,
let firstResponderIndex = visibleRows.first(where: { self.cellForRow(at: $0)?.isActuallyResponder == true }),
options.contains(.excludeFirstResponderCellFromReload) {
return toDeferredUpdatePaths.filter({ $0 != firstResponderIndex })
}
return toDeferredUpdatePaths
}
}
extension UIKit.UICollectionView: EmptyCheckableSequence {
var isEmpty: Bool {
let block: () -> Bool = {
let numberOfSections = (self.dataSource?.numberOfSections?(in: self)) ?? 0
let rowsCount = (0 ..< numberOfSections)
.reduce(0) { $0 + (self.dataSource?.collectionView(self, numberOfItemsInSection: $1) ?? 0) }
return rowsCount == 0
}
if Thread.isMainThread {
return block()
} else {
return DispatchQueue.main.sync(execute: block)
}
}
var safeApplier: SafeApplier {
get {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if let applier = objc_getAssociatedObject(self, &collectionAssociatedObjectHandle) as? SafeApplier {
return applier
} else {
let applier = SafeApplier(associatedTable: self)
objc_setAssociatedObject(self, &collectionAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return applier
}
}
set {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
objc_setAssociatedObject(self, &collectionAssociatedObjectHandle, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
func applyOptions(options: ApplyAnimationOptions, to animations: (cells: CellsAnimations, sections: SectionsAnimations)) -> (cells: CellsAnimations, sections: SectionsAnimations) {
var animations = animations
if let firstResponderIndex = indexPathsForVisibleItems.first(where: { self.cellForItem(at: $0)?.isActuallyResponder == true }) {
if options.contains(.excludeFirstResponderCellFromReload) {
animations.cells.toUpdate = animations.cells.toUpdate.filter({ $0 != firstResponderIndex })
}
if options.contains(.excludeFirstResponderSectionFromReload) {
animations.sections.toUpdate.remove(firstResponderIndex.section)
}
}
return animations
}
func applyOptions(options: ApplyAnimationOptions, toDeferredUpdatePaths: [IndexPath]) -> [IndexPath] {
if let firstResponderIndex = indexPathsForVisibleItems.first(where: { self.cellForItem(at: $0)?.isActuallyResponder == true }),
options.contains(.excludeFirstResponderCellFromReload) {
return toDeferredUpdatePaths.filter({ $0 != firstResponderIndex })
}
return toDeferredUpdatePaths
}
/// Use this for applying changes for UICollectionView.
///
/// - Parameters:
/// - owner: Apply moves to Operation queue, so you need to pass owner for capturing.
/// - newList: New list that should be presented in collection view.
/// - getCurrentListBlock: Block for getting current screen list. Called from main thread.
/// - animator: Instance of TableAnimator for calculating changes.
/// - animated: If you dont want to animate changes, just pass *false*, otherwise, pass *true*.
/// - options: Additional options for animations applying.
/// - from: Initial list, which we got from *getCurrentListBlock()*.
/// - to: New list to set, which you pass in *newList*.
/// - setNewListBlock: Block for changing current screen list to passed *newList*. Called from main thread.
/// - completion: Block for capturing animation completion. Called from main thread.
/// - error: Block for capturing error during changes calculation. When we got error in changes, we call *setNewListBlock* and *collectionView.reloadData()*, then error block called
/// - tableError: TableAnimatorError
public func apply<T, O: AnyObject>(owner: O, newList: [T], animator: TableAnimator<T>, animated: Bool, options: ApplyAnimationOptions = [], getCurrentListBlock: @escaping (_ owner: O) -> [T], setNewListBlock: @escaping ((owner: O, newList: [T])) -> Void, completion: (() -> Void)? = nil, error: ((_ tableError: Error) -> Void)? = nil) {
if options.contains(.cancelPreviousAddedOperations) {
self.getApplyQueue().cancelAllOperations()
}
if options.contains(.withoutActuallyRefreshTable) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner] in
guard let strongO = owner else { return }
setNewListBlock((strongO, newList))
}
}
return
} else if !animated || (self.isEmpty && options.contains(.withoutAnimationForEmptyTable)) {
self.getApplyQueue().addOperation {
DispatchQueue.main.sync { [weak owner, weak self] in
guard let strongO = owner, let strong = self else { return }
setNewListBlock((strongO, newList))
strong.reloadData()
completion?()
}
}
return
}
let safeApplyClosure: (O, DispatchSemaphore, TableAnimations) -> Void = { [weak self] anOwner, semaphore, animations in
guard let strong = self, strong.dataSource != nil else {
return
}
let animations = strong.applyOptions(options: options, to: animations)
strong.performBatchUpdates({
setNewListBlock((anOwner, newList))
strong.insertSections(animations.sections.toInsert)
strong.deleteSections(animations.sections.toDelete)
strong.reloadSections(animations.sections.toUpdate)
for (from, to) in animations.sections.toMove {
strong.moveSection(from, toSection: to)
}
strong.insertItems(at: animations.cells.toInsert)
strong.deleteItems(at: animations.cells.toDelete)
strong.reloadItems(at: animations.cells.toUpdate)
for (from, to) in animations.cells.toMove {
strong.moveItem(at: from, to: to)
}
}, completion: { _ in
if animations.cells.toDeferredUpdate.isEmpty {
completion?()
}
semaphore.signal()
})
}
let safeDeferredApplyClosure: (O, DispatchSemaphore, [IndexPath]) -> Void = { [weak self] _, semaphore, toDeferredUpdate in
guard let strong = self, strong.dataSource != nil else {
return
}
let toDeferredUpdate = strong.applyOptions(options: options, toDeferredUpdatePaths: toDeferredUpdate)
strong.performBatchUpdates({
strong.reloadItems(at: toDeferredUpdate)
}, completion: { _ in
completion?()
semaphore.signal()
})
}
let onAnimationsError: (O, Error) -> Void = { [weak self] anOwner, anError in
setNewListBlock((anOwner, newList))
self?.reloadData()
if let strong = self, strong.dataSource == nil {
return
}
error?(anError)
}
safeApplier.apply(owner: owner,
newList: newList,
options: options,
animator: animator,
getCurrentListBlock: getCurrentListBlock,
mainPerform: safeApplyClosure,
deferredPerform: safeDeferredApplyClosure,
onAnimationsError: onAnimationsError)
}
/// Use this when you need synchronize something with serialized animation queue.
///
/// - Returns: Queue that used for animations synchronizing.
public func getApplyQueue() -> OperationQueue {
return safeApplier.applyQueue
}
/// User this when you want to provide your own operation queue for animations serializing.
/// - Note: You **had to** use serialized queue!
///
/// - Parameter operationQueue: Operation queue that will be used for animatino synchronizing.
/// - Returns: *true* if queue was successfully set, *false* if table already have queue for animations.
public func provideApplyQueue(_ operationQueue: OperationQueue) -> Bool {
objc_sync_enter(monitor)
defer { objc_sync_exit(monitor) }
if (objc_getAssociatedObject(self, &tableAssociatedObjectHandle) as? SafeApplier) != nil {
return false
} else {
let applier = SafeApplier(associatedTable: self, operationQueue: operationQueue)
objc_setAssociatedObject(self, &tableAssociatedObjectHandle, applier, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return true
}
}
}
#endif
| mit |
nguyenantinhbk77/practice-swift | Networking/Downloading an url using NSURLSession - DownloadTask/Downloading an url using NSURLSession - DownloadTask/AppDelegate.swift | 3 | 269 | //
// AppDelegate.swift
// Downloading an url using NSURLSession - DownloadTask
//
// Created by Domenico Solazzo on 16/05/15.
// License MIT
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
}
| mit |
JoshuaRystedt/CalculateEaster | CalculateEasterDate.swift | 1 | 797 | //
// CalculateEasterDate.swift
// Church Cal
//
// Created by Joshua Rystedt on 11/10/15
//
import Foundation
func calculateEasterDateFor(desiredYear: Int) -> NSDate {
// Calculate the date for Easter in any given year
let a = desiredYear % 19
let b = desiredYear / 100
let c = desiredYear % 100
let d = (19 * a + b - b / 4 - ((b - (b + 8) / 25 + 1) / 3) + 15) % 30
let e = (32 + 2 * (b % 4) + 2 * (c / 4) - d - (c % 4)) % 7
let f = d + e - 7 * ((a + 11 * d + 22 * e) / 451) + 114
let month = f / 31
let day = f % 31 + 1
// Create NSDate for Easter
customDateComponents.month = month
customDateComponents.day = day
customDateComponents.year = desiredYear
return calendar.dateFromComponents(customDateComponents)!
}
| gpl-3.0 |
SwiftKitz/Appz | Appz/Appz/Apps/FileApp.swift | 1 | 965 | //
// FileApp.swift
// Pods
//
// Created by Mariam AlJamea on 1/17/16.
// Copyright © 2016 kitz. All rights reserved.
//
public extension Applications {
struct FileApp: ExternalApplication {
public typealias ActionType = Applications.FileApp.Action
public let scheme = "fileapp:"
public let fallbackURL = "http://fileapp.com"
public let appStoreId = "297804694"
public init() {}
}
}
// MARK: - Actions
public extension Applications.FileApp {
enum Action {
case open
}
}
extension Applications.FileApp.Action: ExternalApplicationAction {
public var paths: ActionPaths {
switch self {
case .open:
return ActionPaths(
app: Path(
pathComponents: ["app"],
queryParameters: [:]
),
web: Path()
)
}
}
}
| mit |
natecook1000/swift-compiler-crashes | crashes-duplicates/02269-swift-modulefile-lookupvalue.swift | 11 | 212 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
( ( ( ( A {
}
class c<T where B = D
if c {
| mit |
RayTao/CoreAnimation_Collection | CoreAnimation_CollectionUITests/CoreAnimation_CollectionUITests.swift | 1 | 1394 | //
// CoreAnimation_CollectionUITests.swift
// CoreAnimation_CollectionUITests
//
// Created by ray on 15/12/10.
// Copyright © 2015年 ray. All rights reserved.
//
import XCTest
class CoreAnimation_CollectionUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
if #available(iOS 9.0, *) {
XCUIApplication().launch()
} else {
// Fallback on earlier versions
}
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
gottesmm/swift | validation-test/StdlibUnittest/ChildProcessShutdown/FailIfChildCrashesDuringShutdown.swift | 3 | 877 | // RUN: %target-run-simple-swift 2>&1 | %FileCheck %s
// REQUIRES: executable_test
import StdlibUnittest
#if os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Windows)
import Glibc
#else
import Darwin
#endif
_setTestSuiteFailedCallback() { print("abort()") }
//
// Test that harness aborts when a test crashes if a child process crashes
// after all tests have finished running.
//
var TestSuiteChildCrashes = TestSuite("TestSuiteChildCrashes")
TestSuiteChildCrashes.test("passes") {
atexit {
fatalError("crash at exit")
}
}
// CHECK: [ RUN ] TestSuiteChildCrashes.passes
// CHECK: [ OK ] TestSuiteChildCrashes.passes
// CHECK: TestSuiteChildCrashes: All tests passed
// CHECK: stderr>>> fatal error: crash at exit:
// CHECK: stderr>>> CRASHED: SIG
// CHECK: The child process failed during shutdown, aborting.
// CHECK: abort()
runAllTests()
| apache-2.0 |
lacklock/ResponseMock | RequestDemo/RequestDemo/ImageDataViewController.swift | 1 | 536 | //
// ImageDataViewController.swift
// RequestDemo
//
// Created by 卓同学 on 2017/5/16.
// Copyright © 2017年 卓同学. All rights reserved.
//
import UIKit
class ImageDataViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
let imageURL = "https://img3.doubanio.com/lpic/s29308930.jpg"
let imageData = try! Data(contentsOf: URL(string: imageURL)!)
imageView.image = UIImage(data: imageData)
}
}
| mit |
airspeedswift/swift-compiler-crashes | crashes-fuzzing/00341-cleanupillformedexpression.swift | 1 | 281 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
func f<T> ( ) -> T -> T {
return { x in x 1 {
[ c
}
}
class A {
func a( ) -> {
let : String = {
self.a( )
} ( )
| mit |
AndreMuis/Algorithms | BuildOrder.playground/Contents.swift | 1 | 2535 | //
// Determine the build order for a list of projects with dependencies
//
enum State
{
case NotBuilt
case Visiting
case Built
}
class Project
{
let name : String
var state : State
var dependencies : [Project]
init(name: String)
{
self.name = name
self.state = State.NotBuilt
self.dependencies = [Project]()
}
}
func orderProjects(projects : [Project]) -> [Project]
{
var orderedProjects : [Project] = [Project]()
for project in projects
{
if project.state != State.Built
{
if depthFirstSearch(rootProject: project, orderedProjects: &orderedProjects) == false
{
orderedProjects.removeAll()
break
}
}
}
return orderedProjects
}
func depthFirstSearch(rootProject rootProject : Project, inout orderedProjects : [Project]) -> Bool
{
if (rootProject.state == State.Visiting)
{
return false
}
if rootProject.state == State.NotBuilt
{
rootProject.state = State.Visiting
for project in rootProject.dependencies
{
if depthFirstSearch(rootProject: project, orderedProjects: &orderedProjects) == false
{
return false
}
}
rootProject.state = State.Built
orderedProjects.append(rootProject)
}
return true
}
//
// B - C - D H
// | | | |
// A E - F - G I
//
var projects : [Project] = [Project]()
var aProject = Project(name: "A")
projects.append(aProject)
var bProject = Project(name: "B")
projects.append(bProject)
var cProject = Project(name: "C")
projects.append(cProject)
var dProject = Project(name: "D")
projects.append(dProject)
var eProject = Project(name: "E")
projects.append(eProject)
var fProject = Project(name: "F")
projects.append(fProject)
var gProject = Project(name: "G")
projects.append(gProject)
var hProject = Project(name: "H")
projects.append(hProject)
var iProject = Project(name: "I")
projects.append(iProject)
bProject.dependencies = [aProject]
cProject.dependencies = [bProject, dProject, eProject]
dProject.dependencies = [fProject]
eProject.dependencies = [fProject]
fProject.dependencies = [gProject]
hProject.dependencies = [iProject]
var orderedProjects : [Project] = orderProjects(projects)
for project in orderedProjects
{
print(project.name)
}
gProject.dependencies = [cProject]
orderProjects(projects)
| mit |
MainasuK/Bangumi-M | Percolator/Bangumi M Tests/KeychainAsscessTests.swift | 1 | 1304 | //
// KeychainAsscessTests.swift
// Percolator
//
// Created by Cirno MainasuK on 2016-7-17.
// Copyright © 2016年 Cirno MainasuK. All rights reserved.
//
import XCTest
import KeychainAccess
@testable import Bangumi_M
class KeychainAsscessTests: XCTestCase {
var keychain: Keychain!
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
keychain = Keychain(service: "com.keychainasscess.test")
}
func testSave() {
do {
try keychain.set("password", key: "key")
} catch {
consolePrint(error)
XCTAssertNil(error)
}
}
func testGet() {
let value = String(arc4random_uniform(100) + 1)
keychain["key"] = value
do {
let val = try keychain.get("key")
consolePrint(val)
} catch {
consolePrint(error)
XCTAssertNil(error)
}
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
do {
try keychain.removeAll()
} catch {
consolePrint(error)
}
super.tearDown()
}
}
| mit |
acchou/RxGmail | Example/RxGmail/ViewController.swift | 1 | 516 | import UIKit
import GoogleSignIn
class ViewController: UIViewController, GIDSignInUIDelegate {
@IBOutlet weak var signInButton: GIDSignInButton!
override func viewDidLoad() {
super.viewDidLoad()
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().signInSilently()
signInButton.style = .wide
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit |
johnno1962c/swift-corelibs-foundation | Foundation/NSString.swift | 1 | 66102 | // 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
//
import CoreFoundation
public typealias unichar = UInt16
extension unichar : ExpressibleByUnicodeScalarLiteral {
public typealias UnicodeScalarLiteralType = UnicodeScalar
public init(unicodeScalarLiteral scalar: UnicodeScalar) {
self.init(scalar.value)
}
}
#if os(OSX) || os(iOS)
internal let kCFStringEncodingMacRoman = CFStringBuiltInEncodings.macRoman.rawValue
internal let kCFStringEncodingWindowsLatin1 = CFStringBuiltInEncodings.windowsLatin1.rawValue
internal let kCFStringEncodingISOLatin1 = CFStringBuiltInEncodings.isoLatin1.rawValue
internal let kCFStringEncodingNextStepLatin = CFStringBuiltInEncodings.nextStepLatin.rawValue
internal let kCFStringEncodingASCII = CFStringBuiltInEncodings.ASCII.rawValue
internal let kCFStringEncodingUnicode = CFStringBuiltInEncodings.unicode.rawValue
internal let kCFStringEncodingUTF8 = CFStringBuiltInEncodings.UTF8.rawValue
internal let kCFStringEncodingNonLossyASCII = CFStringBuiltInEncodings.nonLossyASCII.rawValue
internal let kCFStringEncodingUTF16 = CFStringBuiltInEncodings.UTF16.rawValue
internal let kCFStringEncodingUTF16BE = CFStringBuiltInEncodings.UTF16BE.rawValue
internal let kCFStringEncodingUTF16LE = CFStringBuiltInEncodings.UTF16LE.rawValue
internal let kCFStringEncodingUTF32 = CFStringBuiltInEncodings.UTF32.rawValue
internal let kCFStringEncodingUTF32BE = CFStringBuiltInEncodings.UTF32BE.rawValue
internal let kCFStringEncodingUTF32LE = CFStringBuiltInEncodings.UTF32LE.rawValue
internal let kCFStringGraphemeCluster = CFStringCharacterClusterType.graphemeCluster
internal let kCFStringComposedCharacterCluster = CFStringCharacterClusterType.composedCharacterCluster
internal let kCFStringCursorMovementCluster = CFStringCharacterClusterType.cursorMovementCluster
internal let kCFStringBackwardDeletionCluster = CFStringCharacterClusterType.backwardDeletionCluster
internal let kCFStringNormalizationFormD = CFStringNormalizationForm.D
internal let kCFStringNormalizationFormKD = CFStringNormalizationForm.KD
internal let kCFStringNormalizationFormC = CFStringNormalizationForm.C
internal let kCFStringNormalizationFormKC = CFStringNormalizationForm.KC
#endif
extension NSString {
public struct EncodingConversionOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let allowLossy = EncodingConversionOptions(rawValue: 1)
public static let externalRepresentation = EncodingConversionOptions(rawValue: 2)
internal static let failOnPartialEncodingConversion = EncodingConversionOptions(rawValue: 1 << 20)
}
public struct EnumerationOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let byLines = EnumerationOptions(rawValue: 0)
public static let byParagraphs = EnumerationOptions(rawValue: 1)
public static let byComposedCharacterSequences = EnumerationOptions(rawValue: 2)
public static let byWords = EnumerationOptions(rawValue: 3)
public static let bySentences = EnumerationOptions(rawValue: 4)
public static let reverse = EnumerationOptions(rawValue: 1 << 8)
public static let substringNotRequired = EnumerationOptions(rawValue: 1 << 9)
public static let localized = EnumerationOptions(rawValue: 1 << 10)
internal static let forceFullTokens = EnumerationOptions(rawValue: 1 << 20)
}
}
extension NSString {
public struct CompareOptions : OptionSet {
public let rawValue : UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let caseInsensitive = CompareOptions(rawValue: 1)
public static let literal = CompareOptions(rawValue: 2)
public static let backwards = CompareOptions(rawValue: 4)
public static let anchored = CompareOptions(rawValue: 8)
public static let numeric = CompareOptions(rawValue: 64)
public static let diacriticInsensitive = CompareOptions(rawValue: 128)
public static let widthInsensitive = CompareOptions(rawValue: 256)
public static let forcedOrdering = CompareOptions(rawValue: 512)
public static let regularExpression = CompareOptions(rawValue: 1024)
internal func _cfValue(_ fixLiteral: Bool = false) -> CFStringCompareFlags {
#if os(OSX) || os(iOS)
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue: rawValue) : CFStringCompareFlags(rawValue: rawValue).union(.compareNonliteral)
#else
return contains(.literal) || !fixLiteral ? CFStringCompareFlags(rawValue) : CFStringCompareFlags(rawValue) | UInt(kCFCompareNonliteral)
#endif
}
}
}
internal func _createRegexForPattern(_ pattern: String, _ options: NSRegularExpression.Options) -> NSRegularExpression? {
struct local {
static let __NSRegularExpressionCache: NSCache<NSString, NSRegularExpression> = {
let cache = NSCache<NSString, NSRegularExpression>()
cache.name = "NSRegularExpressionCache"
cache.countLimit = 10
return cache
}()
}
let key = "\(options):\(pattern)"
if let regex = local.__NSRegularExpressionCache.object(forKey: key._nsObject) {
return regex
}
do {
let regex = try NSRegularExpression(pattern: pattern, options: options)
local.__NSRegularExpressionCache.setObject(regex, forKey: key._nsObject)
return regex
} catch {
}
return nil
}
internal func _bytesInEncoding(_ str: NSString, _ encoding: String.Encoding, _ fatalOnError: Bool, _ externalRep: Bool, _ lossy: Bool) -> UnsafePointer<Int8>? {
let theRange = NSMakeRange(0, str.length)
var cLength = 0
var used = 0
var options: NSString.EncodingConversionOptions = []
if externalRep {
options.formUnion(.externalRepresentation)
}
if lossy {
options.formUnion(.allowLossy)
}
if !str.getBytes(nil, maxLength: Int.max - 1, usedLength: &cLength, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
if fatalOnError {
fatalError("Conversion on encoding failed")
}
return nil
}
let buffer = malloc(cLength + 1)!.bindMemory(to: Int8.self, capacity: cLength + 1)
if !str.getBytes(buffer, maxLength: cLength, usedLength: &used, encoding: encoding.rawValue, options: options, range: theRange, remaining: nil) {
fatalError("Internal inconsistency; previously claimed getBytes returned success but failed with similar invocation")
}
buffer.advanced(by: cLength).initialize(to: 0)
return UnsafePointer(buffer) // leaked and should be autoreleased via a NSData backing but we cannot here
}
internal func isALineSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x0085 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x0085 || ch == 0x2028 || ch == 0x2029
}
internal func isAParagraphSeparatorTypeCharacter(_ ch: unichar) -> Bool {
if ch > 0x0d && ch < 0x2029 { /* Quick test to cover most chars */
return false
}
return ch == 0x0a || ch == 0x0d || ch == 0x2029
}
open class NSString : NSObject, NSCopying, NSMutableCopying, NSSecureCoding, NSCoding {
private let _cfinfo = _CFInfo(typeID: CFStringGetTypeID())
internal var _storage: String
open var length: Int {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
return _storage.utf16.count
}
open func character(at index: Int) -> unichar {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
return _storage.utf16[start.advanced(by: index)]
}
public override convenience init() {
let characters = Array<unichar>(repeating: 0, count: 1)
self.init(characters: characters, length: 0)
}
internal init(_ string: String) {
_storage = string
}
public convenience required init?(coder aDecoder: NSCoder) {
guard aDecoder.allowsKeyedCoding else {
preconditionFailure("Unkeyed coding is unsupported.")
}
if type(of: aDecoder) == NSKeyedUnarchiver.self || aDecoder.containsValue(forKey: "NS.string") {
let str = aDecoder._decodePropertyListForKey("NS.string") as! String
self.init(string: str)
} else {
let decodedData : Data? = aDecoder.withDecodedUnsafeBufferPointer(forKey: "NS.bytes") {
guard let buffer = $0 else { return nil }
return Data(buffer: buffer)
}
guard let data = decodedData else { return nil }
self.init(data: data, encoding: String.Encoding.utf8.rawValue)
}
}
public required convenience init(string aString: String) {
self.init(aString)
}
open override func copy() -> Any {
return copy(with: nil)
}
open func copy(with zone: NSZone? = nil) -> Any {
return self
}
open override func mutableCopy() -> Any {
return mutableCopy(with: nil)
}
open func mutableCopy(with zone: NSZone? = nil) -> Any {
if type(of: self) === NSString.self || type(of: self) === NSMutableString.self {
if let contents = _fastContents {
return NSMutableString(characters: contents, length: length)
}
}
let characters = UnsafeMutablePointer<unichar>.allocate(capacity: length)
getCharacters(characters, range: NSMakeRange(0, length))
let result = NSMutableString(characters: characters, length: length)
characters.deinitialize()
characters.deallocate(capacity: length)
return result
}
public static var supportsSecureCoding: Bool {
return true
}
open func encode(with aCoder: NSCoder) {
if let aKeyedCoder = aCoder as? NSKeyedArchiver {
aKeyedCoder._encodePropertyList(self, forKey: "NS.string")
} else {
aCoder.encode(self)
}
}
public init(characters: UnsafePointer<unichar>, length: Int) {
_storage = String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
_storage = String(describing: value)
}
public convenience init?(cString nullTerminatedCString: UnsafePointer<Int8>, encoding: UInt) {
self.init(string: CFStringCreateWithCString(kCFAllocatorSystemDefault, nullTerminatedCString, CFStringConvertNSStringEncodingToEncoding(encoding))._swiftObject)
}
internal func _fastCStringContents(_ nullTerminated: Bool) -> UnsafePointer<Int8>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
return unsafeBitCast(_storage._core.startASCII, to: UnsafePointer<Int8>.self)
}
}
return nil
}
internal var _fastContents: UnsafePointer<UniChar>? {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if !_storage._core.isASCII {
return UnsafePointer<UniChar>(_storage._core.startUTF16)
}
}
return nil
}
internal var _encodingCantBeStoredInEightBitCFString: Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return !_storage._core.isASCII
}
return false
}
override open var _cfTypeID: CFTypeID {
return CFStringGetTypeID()
}
open override func isEqual(_ object: Any?) -> Bool {
guard let string = (object as? NSString)?._swiftObject else { return false }
return self.isEqual(to: string)
}
open override var description: String {
return _swiftObject
}
open override var hash: Int {
return Int(bitPattern:CFStringHashNSString(self._cfObject))
}
}
extension NSString {
public func getCharacters(_ buffer: UnsafeMutablePointer<unichar>, range: NSRange) {
for idx in 0..<range.length {
buffer[idx] = character(at: idx + range.location)
}
}
public func substring(from: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.suffix(from: _storage.utf16.startIndex.advanced(by: from)))!
} else {
return substring(with: NSMakeRange(from, length - from))
}
}
public func substring(to: Int) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return String(_storage.utf16.prefix(upTo: _storage.utf16.startIndex
.advanced(by: to)))!
} else {
return substring(with: NSMakeRange(0, to))
}
}
public func substring(with range: NSRange) -> String {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
let start = _storage.utf16.startIndex
let min = start.advanced(by: range.location)
let max = start.advanced(by: range.location + range.length)
return String(decoding: _storage.utf16[min..<max], as: UTF16.self)
} else {
let buff = UnsafeMutablePointer<unichar>.allocate(capacity: range.length)
getCharacters(buff, range: range)
let result = String(describing: buff)
buff.deinitialize()
buff.deallocate(capacity: range.length)
return result
}
}
public func compare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions) -> ComparisonResult {
return compare(string, options: mask, range: NSMakeRange(0, length))
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange) -> ComparisonResult {
return compare(string, options: mask, range: compareRange, locale: nil)
}
public func compare(_ string: String, options mask: CompareOptions, range compareRange: NSRange, locale: Any?) -> ComparisonResult {
var res: CFComparisonResult
if let loc = locale {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), (loc as! NSLocale)._cfObject)
} else {
res = CFStringCompareWithOptionsAndLocale(_cfObject, string._cfObject, CFRange(compareRange), mask._cfValue(true), nil)
}
return ComparisonResult._fromCF(res)
}
public func caseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length))
}
public func localizedCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedCaseInsensitiveCompare(_ string: String) -> ComparisonResult {
return compare(string, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return compare(string, options: [.caseInsensitive, .numeric, .widthInsensitive, .forcedOrdering], range: NSMakeRange(0, length), locale: Locale.current._bridgeToObjectiveC())
}
public func isEqual(to aString: String) -> Bool {
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
return _storage == aString
} else {
return length == aString.length && compare(aString, options: .literal, range: NSMakeRange(0, length)) == .orderedSame
}
}
public func hasPrefix(_ str: String) -> Bool {
return range(of: str, options: .anchored, range: NSMakeRange(0, length)).location != NSNotFound
}
public func hasSuffix(_ str: String) -> Bool {
return range(of: str, options: [.anchored, .backwards], range: NSMakeRange(0, length)).location != NSNotFound
}
public func commonPrefix(with str: String, options mask: CompareOptions = []) -> String {
var currentSubstring: CFMutableString?
let isLiteral = mask.contains(.literal)
var lastMatch = NSRange()
let selfLen = length
let otherLen = str.length
var low = 0
var high = selfLen
var probe = (low + high) / 2
if (probe > otherLen) {
probe = otherLen // A little heuristic to avoid some extra work
}
if selfLen == 0 || otherLen == 0 {
return ""
}
var numCharsBuffered = 0
var arrayBuffer = [unichar](repeating: 0, count: 100)
let other = str._nsObject
return arrayBuffer.withUnsafeMutablePointerOrAllocation(selfLen, fastpath: UnsafeMutablePointer<unichar>(mutating: _fastContents)) { (selfChars: UnsafeMutablePointer<unichar>) -> String in
// Now do the binary search. Note that the probe value determines the length of the substring to check.
while true {
let range = NSMakeRange(0, isLiteral ? probe + 1 : NSMaxRange(rangeOfComposedCharacterSequence(at: probe))) // Extend the end of the composed char sequence
if range.length > numCharsBuffered { // Buffer more characters if needed
getCharacters(selfChars, range: NSMakeRange(numCharsBuffered, range.length - numCharsBuffered))
numCharsBuffered = range.length
}
if currentSubstring == nil {
currentSubstring = CFStringCreateMutableWithExternalCharactersNoCopy(kCFAllocatorSystemDefault, selfChars, range.length, range.length, kCFAllocatorNull)
} else {
CFStringSetExternalCharactersNoCopy(currentSubstring, selfChars, range.length, range.length)
}
if other.range(of: currentSubstring!._swiftObject, options: mask.union(.anchored), range: NSMakeRange(0, otherLen)).length != 0 { // Match
lastMatch = range
low = probe + 1
} else {
high = probe
}
if low >= high {
break
}
probe = (low + high) / 2
}
return lastMatch.length != 0 ? substring(with: lastMatch) : ""
}
}
public func contains(_ str: String) -> Bool {
return range(of: str, options: [], range: NSMakeRange(0, length), locale: nil).location != NSNotFound
}
public func localizedCaseInsensitiveContains(_ str: String) -> Bool {
return range(of: str, options: .caseInsensitive, range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardContains(_ str: String) -> Bool {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current).location != NSNotFound
}
public func localizedStandardRange(of str: String) -> NSRange {
return range(of: str, options: [.caseInsensitive, .diacriticInsensitive], range: NSMakeRange(0, length), locale: Locale.current)
}
public func range(of searchString: String) -> NSRange {
return range(of: searchString, options: [], range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = []) -> NSRange {
return range(of: searchString, options: mask, range: NSMakeRange(0, length), locale: nil)
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
return range(of: searchString, options: mask, range: searchRange, locale: nil)
}
internal func _rangeOfRegularExpressionPattern(regex pattern: String, options mask: CompareOptions, range searchRange: NSRange, locale: Locale?) -> NSRange {
var matchedRange = NSMakeRange(NSNotFound, 0)
let regexOptions: NSRegularExpression.Options = mask.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = mask.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
matchedRange = regex.rangeOfFirstMatch(in: _swiftObject, options: matchingOptions, range: searchRange)
}
return matchedRange
}
public func range(of searchString: String, options mask: CompareOptions = [], range searchRange: NSRange, locale: Locale?) -> NSRange {
let findStrLen = searchString.length
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
if mask.contains(.regularExpression) {
return _rangeOfRegularExpressionPattern(regex: searchString, options: mask, range:searchRange, locale: locale)
}
if searchRange.length == 0 || findStrLen == 0 { // ??? This last item can't be here for correct Unicode compares
return NSMakeRange(NSNotFound, 0)
}
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if let loc = locale {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), loc._cfObject, rangep)
} else {
return CFStringFindWithOptionsAndLocale(_cfObject, searchString._cfObject, CFRange(searchRange), mask._cfValue(true), nil, rangep)
}
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfCharacter(from searchSet: CharacterSet) -> NSRange {
return rangeOfCharacter(from: searchSet, options: [], range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = []) -> NSRange {
return rangeOfCharacter(from: searchSet, options: mask, range: NSMakeRange(0, length))
}
public func rangeOfCharacter(from searchSet: CharacterSet, options mask: CompareOptions = [], range searchRange: NSRange) -> NSRange {
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Bounds Range {\(searchRange.location), \(searchRange.length)} out of bounds; string length \(len)")
var result = CFRange()
let res = withUnsafeMutablePointer(to: &result) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
return CFStringFindCharacterFromSet(_cfObject, searchSet._cfObject, CFRange(searchRange), mask._cfValue(), rangep)
}
if res {
return NSMakeRange(result.location, result.length)
} else {
return NSMakeRange(NSNotFound, 0)
}
}
public func rangeOfComposedCharacterSequence(at index: Int) -> NSRange {
let range = CFStringGetRangeOfCharacterClusterAtIndex(_cfObject, index, kCFStringComposedCharacterCluster)
return NSMakeRange(range.location, range.length)
}
public func rangeOfComposedCharacterSequences(for range: NSRange) -> NSRange {
let length = self.length
var start: Int
var end: Int
if range.location == length {
start = length
} else {
start = rangeOfComposedCharacterSequence(at: range.location).location
}
var endOfRange = NSMaxRange(range)
if endOfRange == length {
end = length
} else {
if range.length > 0 {
endOfRange = endOfRange - 1 // We want 0-length range to be treated same as 1-length range.
}
end = NSMaxRange(rangeOfComposedCharacterSequence(at: endOfRange))
}
return NSMakeRange(start, end - start)
}
public func appending(_ aString: String) -> String {
return _swiftObject + aString
}
public var doubleValue: Double {
var start: Int = 0
var result = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Double) -> Void in
result = value
}
return result
}
public var floatValue: Float {
var start: Int = 0
var result: Float = 0.0
let _ = _swiftObject.scan(CharacterSet.whitespaces, locale: nil, locationToScanFrom: &start) { (value: Float) -> Void in
result = value
}
return result
}
public var intValue: Int32 {
return Scanner(string: _swiftObject).scanInt32() ?? 0
}
public var integerValue: Int {
let scanner = Scanner(string: _swiftObject)
var value: Int = 0
let _ = scanner.scanInt(&value)
return value
}
public var longLongValue: Int64 {
return Scanner(string: _swiftObject).scanInt64() ?? 0
}
public var boolValue: Bool {
let scanner = Scanner(string: _swiftObject)
// skip initial whitespace if present
let _ = scanner.scanCharactersFromSet(.whitespaces)
// scan a single optional '+' or '-' character, followed by zeroes
if scanner.scanString("+") == nil {
let _ = scanner.scanString("-")
}
// scan any following zeroes
let _ = scanner.scanCharactersFromSet(CharacterSet(charactersIn: "0"))
return scanner.scanCharactersFromSet(CharacterSet(charactersIn: "tTyY123456789")) != nil
}
public var uppercased: String {
return uppercased(with: nil)
}
public var lowercased: String {
return lowercased(with: nil)
}
public var capitalized: String {
return capitalized(with: nil)
}
public var localizedUppercase: String {
return uppercased(with: Locale.current)
}
public var localizedLowercase: String {
return lowercased(with: Locale.current)
}
public var localizedCapitalized: String {
return capitalized(with: Locale.current)
}
public func uppercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringUppercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func lowercased(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringLowercase(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
public func capitalized(with locale: Locale?) -> String {
let mutableCopy = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, self._cfObject)!
CFStringCapitalize(mutableCopy, locale?._cfObject ?? nil)
return mutableCopy._swiftObject
}
internal func _getBlockStart(_ startPtr: UnsafeMutablePointer<Int>?, end endPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, forRange range: NSRange, stopAtLineSeparators line: Bool) {
let len = length
var ch: unichar
precondition(range.length <= len && range.location < len - range.length, "Range {\(range.location), \(range.length)} is out of bounds of length \(len)")
if range.location == 0 && range.length == len && contentsEndPtr == nil { // This occurs often
startPtr?.pointee = 0
endPtr?.pointee = range.length
return
}
/* Find the starting point first */
if startPtr != nil {
var start: Int = 0
if range.location == 0 {
start = 0
} else {
var buf = _NSStringBuffer(string: self, start: range.location, end: len)
/* Take care of the special case where start happens to fall right between \r and \n */
ch = buf.currentCharacter
buf.rewind()
if ch == 0x0a && buf.currentCharacter == 0x0d {
buf.rewind()
}
while true {
if line ? isALineSeparatorTypeCharacter(buf.currentCharacter) : isAParagraphSeparatorTypeCharacter(buf.currentCharacter) {
start = buf.location + 1
break
} else if buf.location <= 0 {
start = 0
break
} else {
buf.rewind()
}
}
startPtr!.pointee = start
}
}
if (endPtr != nil || contentsEndPtr != nil) {
var endOfContents = 1
var lineSeparatorLength = 1
var buf = _NSStringBuffer(string: self, start: NSMaxRange(range) - (range.length > 0 ? 1 : 0), end: len)
/* First look at the last char in the range (if the range is zero length, the char after the range) to see if we're already on or within a end of line sequence... */
ch = buf.currentCharacter
if ch == 0x0a {
endOfContents = buf.location
buf.rewind()
if buf.currentCharacter == 0x0d {
lineSeparatorLength = 2
endOfContents -= 1
}
} else {
while true {
if line ? isALineSeparatorTypeCharacter(ch) : isAParagraphSeparatorTypeCharacter(ch) {
endOfContents = buf.location /* This is actually end of contentsRange */
buf.advance() /* OK for this to go past the end */
if ch == 0x0d && buf.currentCharacter == 0x0a {
lineSeparatorLength = 2
}
break
} else if buf.location == len {
endOfContents = len
lineSeparatorLength = 0
break
} else {
buf.advance()
ch = buf.currentCharacter
}
}
}
contentsEndPtr?.pointee = endOfContents
endPtr?.pointee = endOfContents + lineSeparatorLength
}
}
public func getLineStart(_ startPtr: UnsafeMutablePointer<Int>?, end lineEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: lineEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: true)
}
public func lineRange(for range: NSRange) -> NSRange {
var start = 0
var lineEnd = 0
getLineStart(&start, end: &lineEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, lineEnd - start)
}
public func getParagraphStart(_ startPtr: UnsafeMutablePointer<Int>?, end parEndPtr: UnsafeMutablePointer<Int>?, contentsEnd contentsEndPtr: UnsafeMutablePointer<Int>?, for range: NSRange) {
_getBlockStart(startPtr, end: parEndPtr, contentsEnd: contentsEndPtr, forRange: range, stopAtLineSeparators: false)
}
public func paragraphRange(for range: NSRange) -> NSRange {
var start = 0
var parEnd = 0
getParagraphStart(&start, end: &parEnd, contentsEnd: nil, for: range)
return NSMakeRange(start, parEnd - start)
}
public func enumerateSubstrings(in range: NSRange, options opts: EnumerationOptions = [], using block: (String?, NSRange, NSRange, UnsafeMutablePointer<ObjCBool>) -> Void) {
NSUnimplemented()
}
public func enumerateLines(_ block: (String, UnsafeMutablePointer<ObjCBool>) -> Void) {
enumerateSubstrings(in: NSMakeRange(0, length), options:.byLines) { substr, substrRange, enclosingRange, stop in
block(substr!, stop)
}
}
public var utf8String: UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding.utf8, false, false, false)
}
public var fastestEncoding: UInt {
return String.Encoding.unicode.rawValue
}
public var smallestEncoding: UInt {
if canBeConverted(to: String.Encoding.ascii.rawValue) {
return String.Encoding.ascii.rawValue
}
return String.Encoding.unicode.rawValue
}
public func data(using encoding: UInt, allowLossyConversion lossy: Bool = false) -> Data? {
let len = length
var reqSize = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
if !CFStringIsEncodingAvailable(cfStringEncoding) {
return nil
}
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, nil, 0, &reqSize)
if convertedLen != len {
return nil // Not able to do it all...
}
if 0 < reqSize {
var data = Data(count: reqSize)
data.count = data.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Int in
if __CFStringEncodeByteStream(_cfObject, 0, len, true, cfStringEncoding, lossy ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, UnsafeMutablePointer<UInt8>(mutableBytes), reqSize, &reqSize) == convertedLen {
return reqSize
} else {
fatalError("didn't convert all characters")
}
}
return data
}
return Data()
}
public func data(using encoding: UInt) -> Data? {
return data(using: encoding, allowLossyConversion: false)
}
public func canBeConverted(to encoding: UInt) -> Bool {
if encoding == String.Encoding.unicode.rawValue || encoding == String.Encoding.nonLossyASCII.rawValue || encoding == String.Encoding.utf8.rawValue {
return true
}
return __CFStringEncodeByteStream(_cfObject, 0, length, false, CFStringConvertNSStringEncodingToEncoding(encoding), 0, nil, 0, nil) == length
}
public func cString(using encoding: UInt) -> UnsafePointer<Int8>? {
return _bytesInEncoding(self, String.Encoding(rawValue: encoding), false, false, false)
}
public func getCString(_ buffer: UnsafeMutablePointer<Int8>, maxLength maxBufferCount: Int, encoding: UInt) -> Bool {
var used = 0
if type(of: self) == NSString.self || type(of: self) == NSMutableString.self {
if _storage._core.isASCII {
used = min(self.length, maxBufferCount - 1)
_storage._core.startASCII.withMemoryRebound(to: Int8.self,
capacity: used) {
buffer.moveAssign(from: $0, count: used)
}
buffer.advanced(by: used).initialize(to: 0)
return true
}
}
if getBytes(UnsafeMutableRawPointer(buffer), maxLength: maxBufferCount, usedLength: &used, encoding: encoding, options: [], range: NSMakeRange(0, self.length), remaining: nil) {
buffer.advanced(by: used).initialize(to: 0)
return true
}
return false
}
public func getBytes(_ buffer: UnsafeMutableRawPointer?, maxLength maxBufferCount: Int, usedLength usedBufferCount: UnsafeMutablePointer<Int>?, encoding: UInt, options: EncodingConversionOptions = [], range: NSRange, remaining leftover: NSRangePointer?) -> Bool {
var totalBytesWritten = 0
var numCharsProcessed = 0
let cfStringEncoding = CFStringConvertNSStringEncodingToEncoding(encoding)
var result = true
if length > 0 {
if CFStringIsEncodingAvailable(cfStringEncoding) {
let lossyOk = options.contains(.allowLossy)
let externalRep = options.contains(.externalRepresentation)
let failOnPartial = options.contains(.failOnPartialEncodingConversion)
let bytePtr = buffer?.bindMemory(to: UInt8.self, capacity: maxBufferCount)
numCharsProcessed = __CFStringEncodeByteStream(_cfObject, range.location, range.length, externalRep, cfStringEncoding, lossyOk ? (encoding == String.Encoding.ascii.rawValue ? 0xFF : 0x3F) : 0, bytePtr, bytePtr != nil ? maxBufferCount : 0, &totalBytesWritten)
if (failOnPartial && numCharsProcessed < range.length) || numCharsProcessed == 0 {
result = false
}
} else {
result = false /* ??? Need other encodings */
}
}
usedBufferCount?.pointee = totalBytesWritten
leftover?.pointee = NSMakeRange(range.location + numCharsProcessed, range.length - numCharsProcessed)
return result
}
public func maximumLengthOfBytes(using enc: UInt) -> Int {
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let result = CFStringGetMaximumSizeForEncoding(length, cfEnc)
return result == kCFNotFound ? 0 : result
}
public func lengthOfBytes(using enc: UInt) -> Int {
let len = length
var numBytes: CFIndex = 0
let cfEnc = CFStringConvertNSStringEncodingToEncoding(enc)
let convertedLen = __CFStringEncodeByteStream(_cfObject, 0, len, false, cfEnc, 0, nil, 0, &numBytes)
return convertedLen != len ? 0 : numBytes
}
open class var availableStringEncodings: UnsafePointer<UInt> {
struct once {
static let encodings: UnsafePointer<UInt> = {
let cfEncodings = CFStringGetListOfAvailableEncodings()!
var idx = 0
var numEncodings = 0
while cfEncodings.advanced(by: idx).pointee != kCFStringEncodingInvalidId {
idx += 1
numEncodings += 1
}
let theEncodingList = UnsafeMutablePointer<String.Encoding.RawValue>.allocate(capacity: numEncodings + 1)
theEncodingList.advanced(by: numEncodings).pointee = 0 // Terminator
numEncodings -= 1
while numEncodings >= 0 {
theEncodingList.advanced(by: numEncodings).pointee = CFStringConvertEncodingToNSStringEncoding(cfEncodings.advanced(by: numEncodings).pointee)
numEncodings -= 1
}
return UnsafePointer<UInt>(theEncodingList)
}()
}
return once.encodings
}
open class func localizedName(of encoding: UInt) -> String {
if let theString = CFStringGetNameOfEncoding(CFStringConvertNSStringEncodingToEncoding(encoding)) {
// TODO: read the localized version from the Foundation "bundle"
return theString._swiftObject
}
return ""
}
open class var defaultCStringEncoding: UInt {
return CFStringConvertEncodingToNSStringEncoding(CFStringGetSystemEncoding())
}
open var decomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormD)
return string._swiftObject
}
open var precomposedStringWithCanonicalMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormC)
return string._swiftObject
}
open var decomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKD)
return string._swiftObject
}
open var precomposedStringWithCompatibilityMapping: String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringNormalize(string, kCFStringNormalizationFormKC)
return string._swiftObject
}
open func components(separatedBy separator: String) -> [String] {
let len = length
var lrange = range(of: separator, options: [], range: NSMakeRange(0, len))
if lrange.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, lrange.location - srange.location)
array.append(substring(with: trange))
srange.location = lrange.location + lrange.length
srange.length = len - srange.location
lrange = range(of: separator, options: [], range: srange)
if lrange.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func components(separatedBy separator: CharacterSet) -> [String] {
let len = length
var range = rangeOfCharacter(from: separator, options: [], range: NSMakeRange(0, len))
if range.length == 0 {
return [_swiftObject]
} else {
var array = [String]()
var srange = NSMakeRange(0, len)
while true {
let trange = NSMakeRange(srange.location, range.location - srange.location)
array.append(substring(with: trange))
srange.location = range.location + range.length
srange.length = len - srange.location
range = rangeOfCharacter(from: separator, options: [], range: srange)
if range.length == 0 {
break
}
}
array.append(substring(with: srange))
return array
}
}
open func trimmingCharacters(in set: CharacterSet) -> String {
let len = length
var buf = _NSStringBuffer(string: self, start: 0, end: len)
while !buf.isAtEnd,
let character = UnicodeScalar(buf.currentCharacter),
set.contains(character) {
buf.advance()
}
let startOfNonTrimmedRange = buf.location // This points at the first char not in the set
if startOfNonTrimmedRange == len { // Note that this also covers the len == 0 case, which is important to do here before the len-1 in the next line.
return ""
} else if startOfNonTrimmedRange < len - 1 {
buf.location = len - 1
while let character = UnicodeScalar(buf.currentCharacter),
set.contains(character),
buf.location >= startOfNonTrimmedRange {
buf.rewind()
}
let endOfNonTrimmedRange = buf.location
return substring(with: NSMakeRange(startOfNonTrimmedRange, endOfNonTrimmedRange + 1 - startOfNonTrimmedRange))
} else {
return substring(with: NSMakeRange(startOfNonTrimmedRange, 1))
}
}
open func padding(toLength newLength: Int, withPad padString: String, startingAt padIndex: Int) -> String {
let len = length
if newLength <= len { // The simple cases (truncation)
return newLength == len ? _swiftObject : substring(with: NSMakeRange(0, newLength))
}
let padLen = padString.length
if padLen < 1 {
fatalError("empty pad string")
}
if padIndex >= padLen {
fatalError("out of range padIndex")
}
let mStr = CFStringCreateMutableCopy(kCFAllocatorSystemDefault, 0, _cfObject)!
CFStringPad(mStr, padString._cfObject, newLength, padIndex)
return mStr._swiftObject
}
open func folding(options: CompareOptions = [], locale: Locale?) -> String {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, self._cfObject)
CFStringFold(string, options._cfValue(), locale?._cfObject)
return string._swiftObject
}
internal func _stringByReplacingOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range: NSRange) -> String {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.stringByReplacingMatches(in: _swiftObject, options: matchingOptions, range: range, withTemplate: replacement)
}
return ""
}
open func replacingOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> String {
if options.contains(.regularExpression) {
return _stringByReplacingOccurrencesOfRegularExpressionPattern(target, withTemplate: replacement, options: options, range: searchRange)
}
let str = mutableCopy(with: nil) as! NSMutableString
if str.replaceOccurrences(of: target, with: replacement, options: options, range: searchRange) == 0 {
return _swiftObject
} else {
return str._swiftObject
}
}
open func replacingOccurrences(of target: String, with replacement: String) -> String {
return replacingOccurrences(of: target, with: replacement, options: [], range: NSMakeRange(0, length))
}
open func replacingCharacters(in range: NSRange, with replacement: String) -> String {
let str = mutableCopy(with: nil) as! NSMutableString
str.replaceCharacters(in: range, with: replacement)
return str._swiftObject
}
open func applyingTransform(_ transform: String, reverse: Bool) -> String? {
let string = CFStringCreateMutable(kCFAllocatorSystemDefault, 0)!
CFStringReplaceAll(string, _cfObject)
if (CFStringTransform(string, nil, transform._cfObject, reverse)) {
return string._swiftObject
} else {
return nil
}
}
internal func _getExternalRepresentation(_ data: inout Data, _ dest: URL, _ enc: UInt) throws {
let length = self.length
var numBytes = 0
let theRange = NSMakeRange(0, length)
if !getBytes(nil, maxLength: Int.max - 1, usedLength: &numBytes, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteInapplicableStringEncoding.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
var mData = Data(count: numBytes)
// The getBytes:... call should hopefully not fail, given it succeeded above, but check anyway (mutable string changing behind our back?)
var used = 0
// This binds mData memory to UInt8 because Data.withUnsafeMutableBytes does not handle raw pointers.
try mData.withUnsafeMutableBytes { (mutableBytes: UnsafeMutablePointer<UInt8>) -> Void in
if !getBytes(mutableBytes, maxLength: numBytes, usedLength: &used, encoding: enc, options: [], range: theRange, remaining: nil) {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [
NSURLErrorKey: dest,
])
}
}
data = mData
}
internal func _writeTo(_ url: URL, _ useAuxiliaryFile: Bool, _ enc: UInt) throws {
var data = Data()
try _getExternalRepresentation(&data, url, enc)
try data.write(to: url, options: useAuxiliaryFile ? .atomic : [])
}
open func write(to url: URL, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(url, useAuxiliaryFile, enc)
}
open func write(toFile path: String, atomically useAuxiliaryFile: Bool, encoding enc: UInt) throws {
try _writeTo(URL(fileURLWithPath: path), useAuxiliaryFile, enc)
}
public convenience init(charactersNoCopy characters: UnsafeMutablePointer<unichar>, length: Int, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// ignore the no-copy-ness
self.init(characters: characters, length: length)
if freeBuffer { // cant take a hint here...
free(UnsafeMutableRawPointer(characters))
}
}
public convenience init?(utf8String nullTerminatedCString: UnsafePointer<Int8>) {
let count = Int(strlen(nullTerminatedCString))
if let str = nullTerminatedCString.withMemoryRebound(to: UInt8.self, capacity: count, {
let buffer = UnsafeBufferPointer<UInt8>(start: $0, count: count)
return String._fromCodeUnitSequence(UTF8.self, input: buffer)
}) as String?
{
self.init(str)
} else {
return nil
}
}
public convenience init(format: String, arguments argList: CVaListPointer) {
let str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)!
self.init(str._swiftObject)
}
public convenience init(format: String, locale: AnyObject?, arguments argList: CVaListPointer) {
let str: CFString
if let loc = locale {
if type(of: loc) === NSLocale.self || type(of: loc) === NSDictionary.self {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, unsafeBitCast(loc, to: CFDictionary.self), format._cfObject, argList)
} else {
fatalError("locale parameter must be a NSLocale or a NSDictionary")
}
} else {
str = CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, argList)
}
self.init(str._swiftObject)
}
public convenience init(format: NSString, _ args: CVarArg...) {
let str = withVaList(args) { (vaPtr) -> CFString! in
CFStringCreateWithFormatAndArguments(kCFAllocatorSystemDefault, nil, format._cfObject, vaPtr)
}!
self.init(str._swiftObject)
}
public convenience init?(data: Data, encoding: UInt) {
if data.isEmpty {
self.init("")
} else {
guard let cf = data.withUnsafeBytes({ (bytes: UnsafePointer<UInt8>) -> CFString? in
return CFStringCreateWithBytes(kCFAllocatorDefault, bytes, data.count, CFStringConvertNSStringEncodingToEncoding(encoding), true)
}) else { return nil }
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
}
public convenience init?(bytes: UnsafeRawPointer, length len: Int, encoding: UInt) {
let bytePtr = bytes.bindMemory(to: UInt8.self, capacity: len)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, len, CFStringConvertNSStringEncodingToEncoding(encoding), true) else {
return nil
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
return nil
}
}
public convenience init?(bytesNoCopy bytes: UnsafeMutableRawPointer, length len: Int, encoding: UInt, freeWhenDone freeBuffer: Bool) /* "NoCopy" is a hint */ {
// just copy for now since the internal storage will be a copy anyhow
self.init(bytes: bytes, length: len, encoding: encoding)
if freeBuffer { // dont take the hint
free(bytes)
}
}
public convenience init(contentsOf url: URL, encoding enc: UInt) throws {
let readResult = try NSData(contentsOf: url, options: [])
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity: readResult.length)
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr, readResult.length, CFStringConvertNSStringEncodingToEncoding(enc), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, encoding enc: UInt) throws {
try self.init(contentsOf: URL(fileURLWithPath: path), encoding: enc)
}
public convenience init(contentsOf url: URL, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
let readResult = try NSData(contentsOf: url, options:[])
let encoding: UInt
let offset: Int
let bytePtr = readResult.bytes.bindMemory(to: UInt8.self, capacity:readResult.length)
if readResult.length >= 4 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE && bytePtr[2] == 0x00 && bytePtr[3] == 0x00 {
encoding = String.Encoding.utf32LittleEndian.rawValue
offset = 4
}
else if readResult.length >= 2 && bytePtr[0] == 0xFE && bytePtr[1] == 0xFF {
encoding = String.Encoding.utf16BigEndian.rawValue
offset = 2
}
else if readResult.length >= 2 && bytePtr[0] == 0xFF && bytePtr[1] == 0xFE {
encoding = String.Encoding.utf16LittleEndian.rawValue
offset = 2
}
else if readResult.length >= 4 && bytePtr[0] == 0x00 && bytePtr[1] == 0x00 && bytePtr[2] == 0xFE && bytePtr[3] == 0xFF {
encoding = String.Encoding.utf32BigEndian.rawValue
offset = 4
}
else {
//Need to work on more conditions. This should be the default
encoding = String.Encoding.utf8.rawValue
offset = 0
}
enc?.pointee = encoding
// Since the encoding being passed includes the byte order the BOM wont be checked or skipped, so pass offset to
// manually skip the BOM header.
guard let cf = CFStringCreateWithBytes(kCFAllocatorDefault, bytePtr + offset, readResult.length - offset,
CFStringConvertNSStringEncodingToEncoding(encoding), true) else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to create a string using the specified encoding."
])
}
var str: String?
if String._conditionallyBridgeFromObjectiveC(cf._nsObject, result: &str) {
self.init(str!)
} else {
throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadInapplicableStringEncoding.rawValue, userInfo: [
"NSDebugDescription" : "Unable to bridge CFString to String."
])
}
}
public convenience init(contentsOfFile path: String, usedEncoding enc: UnsafeMutablePointer<UInt>?) throws {
try self.init(contentsOf: URL(fileURLWithPath: path), usedEncoding: enc)
}
}
extension NSString : ExpressibleByStringLiteral { }
open class NSMutableString : NSString {
open func replaceCharacters(in range: NSRange, with aString: String) {
guard type(of: self) === NSString.self || type(of: self) === NSMutableString.self else {
NSRequiresConcreteImplementation()
}
let start = _storage.utf16.startIndex
let min = _storage.utf16.index(start, offsetBy: range.location).samePosition(in: _storage)!
let max = _storage.utf16.index(start, offsetBy: range.location + range.length).samePosition(in: _storage)!
_storage.replaceSubrange(min..<max, with: aString)
}
public required override init(characters: UnsafePointer<unichar>, length: Int) {
super.init(characters: characters, length: length)
}
public required init(capacity: Int) {
super.init(characters: [], length: 0)
}
public convenience required init?(coder aDecoder: NSCoder) {
guard let str = NSString(coder: aDecoder) else {
return nil
}
self.init(string: String._unconditionallyBridgeFromObjectiveC(str))
}
public required convenience init(unicodeScalarLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required convenience init(extendedGraphemeClusterLiteral value: StaticString) {
self.init(stringLiteral: value)
}
public required init(stringLiteral value: StaticString) {
if value.hasPointerRepresentation {
super.init(String._fromWellFormedCodeUnitSequence(UTF8.self, input: UnsafeBufferPointer(start: value.utf8Start, count: Int(value.utf8CodeUnitCount))))
} else {
var uintValue = value.unicodeScalar.value
super.init(String._fromWellFormedCodeUnitSequence(UTF32.self, input: UnsafeBufferPointer(start: &uintValue, count: 1)))
}
}
public required init(string aString: String) {
super.init(aString)
}
internal func appendCharacters(_ characters: UnsafePointer<unichar>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
} else {
replaceCharacters(in: NSMakeRange(self.length, 0), with: String._fromWellFormedCodeUnitSequence(UTF16.self, input: UnsafeBufferPointer(start: characters, count: length)))
}
}
internal func _cfAppendCString(_ characters: UnsafePointer<Int8>, length: Int) {
if type(of: self) == NSMutableString.self {
_storage.append(String(cString: characters))
}
}
}
extension NSMutableString {
public func insert(_ aString: String, at loc: Int) {
replaceCharacters(in: NSMakeRange(loc, 0), with: aString)
}
public func deleteCharacters(in range: NSRange) {
replaceCharacters(in: range, with: "")
}
public func append(_ aString: String) {
replaceCharacters(in: NSMakeRange(length, 0), with: aString)
}
public func setString(_ aString: String) {
replaceCharacters(in: NSMakeRange(0, length), with: aString)
}
internal func _replaceOccurrencesOfRegularExpressionPattern(_ pattern: String, withTemplate replacement: String, options: CompareOptions, range searchRange: NSRange) -> Int {
let regexOptions: NSRegularExpression.Options = options.contains(.caseInsensitive) ? .caseInsensitive : []
let matchingOptions: NSRegularExpression.MatchingOptions = options.contains(.anchored) ? .anchored : []
if let regex = _createRegexForPattern(pattern, regexOptions) {
return regex.replaceMatches(in: self, options: matchingOptions, range: searchRange, withTemplate: replacement)
}
return 0
}
public func replaceOccurrences(of target: String, with replacement: String, options: CompareOptions = [], range searchRange: NSRange) -> Int {
let backwards = options.contains(.backwards)
let len = length
precondition(searchRange.length <= len && searchRange.location <= len - searchRange.length, "Search range is out of bounds")
if options.contains(.regularExpression) {
return _replaceOccurrencesOfRegularExpressionPattern(target, withTemplate:replacement, options:options, range: searchRange)
}
if let findResults = CFStringCreateArrayWithFindResults(kCFAllocatorSystemDefault, _cfObject, target._cfObject, CFRange(searchRange), options._cfValue(true)) {
let numOccurrences = CFArrayGetCount(findResults)
for cnt in 0..<numOccurrences {
let rangePtr = CFArrayGetValueAtIndex(findResults, backwards ? cnt : numOccurrences - cnt - 1)
replaceCharacters(in: NSRange(rangePtr!.load(as: CFRange.self)), with: replacement)
}
return numOccurrences
} else {
return 0
}
}
public func applyTransform(_ transform: String, reverse: Bool, range: NSRange, updatedRange resultingRange: NSRangePointer?) -> Bool {
var cfRange = CFRangeMake(range.location, range.length)
return withUnsafeMutablePointer(to: &cfRange) { (rangep: UnsafeMutablePointer<CFRange>) -> Bool in
if CFStringTransform(_cfMutableObject, rangep, transform._cfObject, reverse) {
resultingRange?.pointee.location = rangep.pointee.location
resultingRange?.pointee.length = rangep.pointee.length
return true
}
return false
}
}
}
extension String {
// this is only valid for the usage for CF since it expects the length to be in unicode characters instead of grapheme clusters "✌🏾".utf16.count = 3 and CFStringGetLength(CFSTR("✌🏾")) = 3 not 1 as it would be represented with grapheme clusters
internal var length: Int {
return utf16.count
}
}
extension NSString : _CFBridgeable, _SwiftBridgeable {
typealias SwiftType = String
internal var _cfObject: CFString { return unsafeBitCast(self, to: CFString.self) }
internal var _swiftObject: String { return String._unconditionallyBridgeFromObjectiveC(self) }
}
extension NSMutableString {
internal var _cfMutableObject: CFMutableString { return unsafeBitCast(self, to: CFMutableString.self) }
}
extension CFString : _NSBridgeable, _SwiftBridgeable {
typealias NSType = NSString
typealias SwiftType = String
internal var _nsObject: NSType { return unsafeBitCast(self, to: NSString.self) }
internal var _swiftObject: String { return _nsObject._swiftObject }
}
extension String : _NSBridgeable, _CFBridgeable {
typealias NSType = NSString
typealias CFType = CFString
internal var _nsObject: NSType { return _bridgeToObjectiveC() }
internal var _cfObject: CFType { return _nsObject._cfObject }
}
#if !(os(OSX) || os(iOS))
extension String {
public func hasPrefix(_ prefix: String) -> Bool {
if prefix.isEmpty {
return true
}
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, prefix._cfObject,
range, opts, nil)
}
public func hasSuffix(_ suffix: String) -> Bool {
if suffix.isEmpty {
return true
}
let cfstring = self._cfObject
let range = CFRangeMake(0, CFStringGetLength(cfstring))
let opts = CFStringCompareFlags(
kCFCompareAnchored | kCFCompareBackwards | kCFCompareNonliteral)
return CFStringFindWithOptions(cfstring, suffix._cfObject,
range, opts, nil)
}
}
#endif
extension NSString : _StructTypeBridgeable {
public typealias _StructType = String
public func _bridgeToSwift() -> _StructType {
return _StructType._unconditionallyBridgeFromObjectiveC(self)
}
}
| apache-2.0 |
AltiAntonov/LayoutManager | Source/Frame.swift | 1 | 1329 | //
// Frame.swift
// LayoutManager
//
// Created by Altimir Antonov on 6/2/16.
// Copyright © 2016 Altimir Antonov. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
public protocol Frameable : class {
var frame: CGRect { get set }
var superFrame: CGRect { get }
var x: CGFloat { get }
var xMid: CGFloat { get }
var xMax: CGFloat { get }
var y: CGFloat { get }
var yMid: CGFloat { get }
var yMax: CGFloat { get }
var width: CGFloat { get }
var height: CGFloat { get }
func setDimensionAutomatically()
}
extension Frameable {
public var x: CGFloat {
return CGRectGetMinX(frame)
}
public var xMid: CGFloat {
return CGRectGetMinX(frame) + (CGRectGetWidth(frame) / 2.0)
}
public var xMax: CGFloat {
return CGRectGetMaxX(frame)
}
public var y: CGFloat {
return CGRectGetMinY(frame)
}
public var yMid: CGFloat {
return CGRectGetMinY(frame) + (CGRectGetHeight(frame) / 2.0)
}
public var yMax: CGFloat {
return CGRectGetMaxY(frame)
}
public var width: CGFloat {
return CGRectGetWidth(frame)
}
public var height: CGFloat {
return CGRectGetHeight(frame)
}
}
| mit |
tedvb/Cubic | Cubic/Drawing.swift | 1 | 5126 | //
// Drawing.swift
// Cubic
//
// Created by Ted von Bevern on 5/27/15.
// Copyright (c) 2015 Ted von Bevern. All rights reserved.
//
import Foundation
import SceneKit
func drawLUT(lut: LUT, numInterpPoints: Int) -> [SCNNode] {
var lutNodes = [SCNNode]()
for i in 0...numInterpPoints {
var lutNode = SCNNode()
for point in lut.points {
var sphereGeometry = SCNSphere(radius: 0.01)
var red: CGFloat
var green: CGFloat
var blue: CGFloat
//interpolate r, g, b values for each point based on i / numInterpPoints
red = CGFloat((point.red - point.originRed) * Double(i) / Double(numInterpPoints) + point.originRed)
green = CGFloat((point.green - point.originGreen) * Double(i) / Double(numInterpPoints) + point.originGreen)
blue = CGFloat((point.blue - point.originBlue) * Double(i) / Double(numInterpPoints) + point.originBlue)
sphereGeometry.firstMaterial!.diffuse.contents = NSColor(red: red, green: green, blue: blue, alpha: 1.0)
sphereGeometry.segmentCount = 5
var sphereNode = SCNNode(geometry: sphereGeometry)
sphereNode.position = SCNVector3Make(red, green, blue)
lutNode.addChildNode(sphereNode)
}
lutNodes.append(lutNode)
}
return lutNodes
}
func drawFrame() -> SCNNode {
var frameNode = SCNNode()
var edgeNodes = [SCNNode]()
for var i = 0; i < 9; i++ {
var geo = SCNCylinder(radius: 0.001, height: 1.0)
geo.firstMaterial!.diffuse.contents = NSColor.whiteColor()
edgeNodes.append(SCNNode(geometry: geo))
edgeNodes[i].pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(-0.5), CGFloat(0))
}
edgeNodes[0].rotation = SCNVector4Make(CGFloat(0), CGFloat(0), CGFloat(1.0), CGFloat(-M_PI_2))
edgeNodes[0].position = SCNVector3Make(CGFloat(0), CGFloat(1.0), CGFloat(0))
edgeNodes[1].position = SCNVector3Make(CGFloat(1.0), CGFloat(0), CGFloat(0))
edgeNodes[2].rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0), CGFloat(0), CGFloat(M_PI_2))
edgeNodes[2].position = SCNVector3Make(CGFloat(1.0), CGFloat(0), CGFloat(0))
edgeNodes[3].rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0), CGFloat(0), CGFloat(M_PI_2))
edgeNodes[3].position = SCNVector3Make(CGFloat(0), CGFloat(1.0), CGFloat(0))
edgeNodes[4].rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0), CGFloat(0), CGFloat(M_PI_2))
edgeNodes[4].position = SCNVector3Make(CGFloat(1.0), CGFloat(1.0), CGFloat(0))
edgeNodes[5].position = SCNVector3Make(CGFloat(0), CGFloat(0), CGFloat(1.0))
edgeNodes[6].rotation = SCNVector4Make(CGFloat(0), CGFloat(0), CGFloat(1.0), CGFloat(-M_PI_2))
edgeNodes[6].position = SCNVector3Make(CGFloat(0), CGFloat(1.0), CGFloat(1.0))
edgeNodes[7].position = SCNVector3Make(CGFloat(1.0), CGFloat(0), CGFloat(1.0))
edgeNodes[8].rotation = SCNVector4Make(CGFloat(0), CGFloat(0), CGFloat(1.0), CGFloat(-M_PI_2))
edgeNodes[8].position = SCNVector3Make(CGFloat(0), CGFloat(0), CGFloat(1.0))
for node in edgeNodes {
frameNode.addChildNode(node)
}
return frameNode
}
func drawAxes() -> SCNNode {
var axisNode = SCNNode()
let rCylinder = SCNCylinder(radius: 0.001, height: 1.0)
let gCylinder = SCNCylinder(radius: 0.001, height: 1.0)
let bCylinder = SCNCylinder(radius: 0.001, height: 1.0)
rCylinder.firstMaterial!.diffuse.contents = NSColor.redColor()
gCylinder.firstMaterial!.diffuse.contents = NSColor.greenColor()
bCylinder.firstMaterial!.diffuse.contents = NSColor.blueColor()
var rAxisNode = SCNNode(geometry: rCylinder)
var gAxisNode = SCNNode(geometry: gCylinder)
var bAxisNode = SCNNode(geometry: bCylinder)
rAxisNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(0.5), CGFloat(0.0))
gAxisNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(-0.5), CGFloat(0.0))
bAxisNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0), CGFloat(-0.5), CGFloat(0.0))
rAxisNode.rotation = SCNVector4Make(CGFloat(0.0), CGFloat(0.0), CGFloat(1.0), CGFloat(M_PI_2))
gAxisNode.rotation = SCNVector4Make(CGFloat(0.0), CGFloat(1.0), CGFloat(0.0), CGFloat(M_PI_2))
bAxisNode.rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0.0), CGFloat(0.0), CGFloat(M_PI_2))
axisNode.addChildNode(rAxisNode)
axisNode.addChildNode(gAxisNode)
axisNode.addChildNode(bAxisNode)
return axisNode
}
func drawDiagonal() -> SCNNode {
let diagCylinder = SCNCylinder(radius: 0.001, height: sqrt(3))
diagCylinder.firstMaterial!.diffuse.contents = NSColor.whiteColor()
var diagNode = SCNNode(geometry: diagCylinder)
diagNode.pivot = SCNMatrix4MakeTranslation(CGFloat(0.0), CGFloat(-sqrt(3)/2.0), CGFloat(0.0))
diagNode.rotation = SCNVector4Make(CGFloat(1.0), CGFloat(0.0), CGFloat(-1.0), CGFloat(0.95531))
return diagNode
}
| mit |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 05 - Transition Coordinator Updates/KhromaLike/KhromaLike/CollectionView/SwatchSelection.swift | 1 | 1447 | /*
* Copyright (c) 2014 Razeware LLC
*
* 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
protocol ColorSwatchSelectionDelegate : class {
func didSelect(swatch: ColorSwatch, sender: AnyObject?)
}
protocol ColorSwatchSelector : class {
var swatchSelectionDelegate: ColorSwatchSelectionDelegate? { get set }
}
protocol ColorSwatchSelectable: class {
var colorSwatch: ColorSwatch? { get set }
} | mit |
lanjing99/iOSByTutorials | iOS 8 by tutorials/Chapter 15 - Beginning CloudKit/BabiFud-Final/BabiFud/DetailViewController.swift | 1 | 11705 | /*
* Copyright (c) 2014 Razeware LLC
*
* 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
import UIWidgets
import CloudKit
class DetailViewController: UITableViewController, UISplitViewControllerDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var masterPopoverController: UIPopoverController? = nil
@IBOutlet var coverView: UIImageView!
@IBOutlet var titleLabel: UILabel!
@IBOutlet var starRating: StarRatingControl!
@IBOutlet var kidsMenuButton: CheckedButton!
@IBOutlet var healthyChoiceButton: CheckedButton!
@IBOutlet var womensRoomButton: UIButton!
@IBOutlet var mensRoomButton: UIButton!
@IBOutlet var boosterButton: UIButton!
@IBOutlet var highchairButton: UIButton!
@IBOutlet var addPhotoButton: UIButton!
@IBOutlet var photoScrollView: UIScrollView!
@IBOutlet var noteTextView: UITextView!
var detailItem: Establishment! {
didSet {
if self.masterPopoverController != nil {
self.masterPopoverController!.dismissPopoverAnimated(true)
}
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail: Establishment = self.detailItem {
title = detail.name
detail.loadCoverPhoto() { image in
dispatch_async(dispatch_get_main_queue()) {
self.coverView.image = image
}
}
titleLabel.text = detail.name
starRating.maxRating = 5
starRating.enabled = false
Model.sharedInstance().userInfo.loggedInToICloud() {
accountStatus, error in
let enabled = accountStatus == .Available || accountStatus == .CouldNotDetermine
self.starRating.enabled = enabled
self.healthyChoiceButton.enabled = enabled
self.kidsMenuButton.enabled = enabled
self.mensRoomButton.enabled = enabled
self.womensRoomButton.enabled = enabled
self.boosterButton.enabled = enabled
self.highchairButton.enabled = enabled
self.addPhotoButton.enabled = enabled
}
self.kidsMenuButton.checked = detailItem.kidsMenu
self.healthyChoiceButton.checked = detailItem.healthyChoice
self.womensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Womens).boolValue
self.mensRoomButton.selected = (detailItem.changingTable() & ChangingTableLocation.Mens).boolValue
self.highchairButton.selected = (detailItem.seatingType() & SeatingType.HighChair).boolValue
self.boosterButton.selected = (detailItem.seatingType() & SeatingType.Booster).boolValue
detail.fetchRating() { rating, isUser in
dispatch_async(dispatch_get_main_queue()) {
self.starRating.maxRating = 5
self.starRating.rating = Float(rating)
self.starRating.setNeedsDisplay()
self.starRating.emptyColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
self.starRating.solidColor = isUser ? UIColor.yellowColor() : UIColor.whiteColor()
}
}
detail.fetchPhotos() { assets in
if assets != nil {
var x = 10
for record in assets {
if let asset = record.objectForKey("Photo") as? CKAsset {
let image: UIImage? = UIImage(contentsOfFile: asset.fileURL.path!)
if image != nil {
let imView = UIImageView(image: image)
imView.frame = CGRect(x: x, y: 0, width: 60, height: 60)
imView.clipsToBounds = true
imView.layer.cornerRadius = 8
x += 70
imView.layer.borderWidth = 0.0
//if the user has discovered the photo poster, color the photo with a green border
if let photoUserRef = record.objectForKey("User") as? CKReference {
let photoUserId = photoUserRef.recordID
let contactList = Model.sharedInstance().userInfo.contacts
let contacts = contactList.filter {$0.userRecordID == photoUserId}
if contacts.count > 0 {
imView.layer.borderWidth = 1.0
imView.layer.borderColor = UIColor.greenColor().CGColor
}
}
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(imView)
}
}
}
}
}
}
detail.fetchNote() { note in
println("note \(note)")
if let noteText = note {
dispatch_async(dispatch_get_main_queue()) {
self.noteTextView.text = noteText
}
}
}
}
}
func saveRating(rating: NSNumber) {
// 1
let ratingRecord = CKRecord(recordType: "Rating")
// 2
ratingRecord.setObject(rating, forKey: "Rating")
// 3
let ref = CKReference(record: self.detailItem.record,
action: .DeleteSelf)
// 4
ratingRecord.setObject(ref, forKey: "Establishment")
// 5
Model.sharedInstance().userInfo.userID() {
userID, error in
if let userRecord = userID {
//6
let userRef = CKReference(recordID: userRecord,
action: .None)
ratingRecord.setObject(userRef, forKey: "User")
// 7
self.detailItem.database.saveRecord(ratingRecord) {
record, error in
if error != nil {
println("error saving rating: (\rating)")
} else {
dispatch_async(dispatch_get_main_queue()) {
self.starRating.emptyColor = UIColor.yellowColor()
self.starRating.solidColor = UIColor.yellowColor()
self.starRating.setNeedsDisplay()
}
}
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
coverView.clipsToBounds = true
coverView.layer.cornerRadius = 10.0
starRating.editingChangedBlock = { rating in
self.saveRating(rating)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
configureView()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "EditNote" {
let noteController = segue.destinationViewController as NotesViewController
noteController.establishment = self.detailItem
}
}
// #pragma mark - Split view
func splitViewController(splitController: UISplitViewController, willHideViewController viewController: UIViewController, withBarButtonItem barButtonItem: UIBarButtonItem, forPopoverController popoverController: UIPopoverController) {
barButtonItem.title = NSLocalizedString("Places", comment: "Places")
self.navigationItem.setLeftBarButtonItem(barButtonItem, animated: true)
self.masterPopoverController = popoverController
}
func splitViewController(splitController: UISplitViewController, willShowViewController viewController: UIViewController, invalidatingBarButtonItem barButtonItem: UIBarButtonItem) {
// Called when the view is shown again in the split view, invalidating the button and popover controller.
self.navigationItem.setLeftBarButtonItem(nil, animated: true)
self.masterPopoverController = nil
}
func splitViewController(splitController: UISplitViewController, collapseSecondaryViewController secondaryViewController: UIViewController, ontoPrimaryViewController primaryViewController: UIViewController) -> Bool {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
// #pragma mark - Image Picking
@IBAction func addPhoto(sender: AnyObject) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = .SavedPhotosAlbum
self.presentViewController(imagePicker, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]!) {
dismissViewControllerAnimated(true, completion: nil)
if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
self.addPhotoToEstablishment(selectedImage)
}
}
}
func generateFileURL() -> NSURL {
let fileManager = NSFileManager.defaultManager()
let fileArray: NSArray = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
let fileURL = fileArray.lastObject?.URLByAppendingPathComponent(NSUUID().UUIDString).URLByAppendingPathExtension("jpg")
if let filePath = fileArray.lastObject?.path {
if !fileManager.fileExistsAtPath(filePath!) {
fileManager.createDirectoryAtPath(filePath!, withIntermediateDirectories: true, attributes: nil, error: nil)
}
}
return fileURL!
}
func addNewPhotoToScrollView(photo:UIImage) {
let newImView = UIImageView(image: photo)
let offset = self.detailItem.assetCount * 70 + 10
var frame: CGRect = CGRect(x: offset, y: 0, width: 60, height: 60)
newImView.frame = frame
newImView.clipsToBounds = true
newImView.layer.cornerRadius = 8
dispatch_async(dispatch_get_main_queue()) {
self.photoScrollView.addSubview(newImView)
self.photoScrollView.contentSize = CGSize(width: CGRectGetMaxX(frame), height: CGRectGetHeight(frame));
}
}
func addPhotoToEstablishment(photo: UIImage) {
//1
let fileURL = generateFileURL()
let data = UIImageJPEGRepresentation(photo, 0.9)
var error : NSError?
let wrote = data.writeToURL(fileURL, options: .AtomicWrite, error: &error)
if (error != nil) {
UIAlertView(title: "Error Saving Photo",
message: error?.localizedDescription, delegate: nil,
cancelButtonTitle: "OK").show()
return
}
// 2
let asset = CKAsset(fileURL: fileURL)
// 3
let ref = CKReference(record: self.detailItem.record,
action: .DeleteSelf)
// 4
Model.sharedInstance().userInfo.userID() {
userID, error in
if let userRecordID = userID {
let userRef = CKReference(recordID: userRecordID, action: .None)
// 5
let record = CKRecord(recordType: "EstablishmentPhoto")
record.setObject(asset, forKey: "Photo")
// 6
record.setObject(ref, forKey: "Establishment")
record.setObject(userRef, forKey: "User")
// 7
self.detailItem.database.saveRecord(record) {record, error in
if error == nil {
// 8
self.addNewPhotoToScrollView(photo)
}
NSFileManager.defaultManager().removeItemAtURL(fileURL, error: nil)
}
}
}
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.